Print all leaf nodes of a Binary Tree from left to right | Binary tree node ; Function to print leaf nodes from left to right ; If node is null , return ; If node is leaf node , print its data ; If left child exists , check for leaf recursively ; If right child exists , check for leaf recursively ; Driver Code ; Let us create binary tree shown in above diagram ; print leaf nodes of the given tree
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printLeafNodes ( root : Node ) -> None : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( not root . left and not root . right ) : NEW_LINE INDENT print ( root . data , end = " ▁ " ) NEW_LINE return NEW_LINE DEDENT if root . left : NEW_LINE INDENT printLeafNodes ( root . left ) NEW_LINE DEDENT if root . right : NEW_LINE INDENT printLeafNodes ( root . right ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . right . left = Node ( 5 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE root . right . left . left = Node ( 6 ) NEW_LINE root . right . left . right = Node ( 7 ) NEW_LINE root . right . right . left = Node ( 9 ) NEW_LINE root . right . right . right = Node ( 10 ) NEW_LINE printLeafNodes ( root ) NEW_LINE DEDENT