Boundary Traversal of binary tree | A binary tree node ; A simple function to print leaf nodes of a Binary Tree ; Print it if it is a leaf node ; A function to print all left boundary nodes , except a leaf node . Print the nodes in TOP DOWN manner ; to ensure top down order , print the node before calling itself for left subtree ; A function to print all right boundary nodes , except a leaf node . Print the nodes in BOTTOM UP manner ; to ensure bottom up order , first call for right subtree , then print this node ; A function to do boundary traversal of a given binary tree ; Print the left boundary in top - down manner ; Print all leaf nodes ; Print the right boundary in bottom - up manner ; Driver program to test above function
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 printLeaves ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT printLeaves ( root . left ) NEW_LINE if root . left is None and root . right is None : NEW_LINE INDENT print ( root . data ) , NEW_LINE DEDENT printLeaves ( root . right ) NEW_LINE DEDENT DEDENT def printBoundaryLeft ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT if ( root . left ) : NEW_LINE INDENT print ( root . data ) NEW_LINE printBoundaryLeft ( root . left ) NEW_LINE DEDENT elif ( root . right ) : NEW_LINE INDENT print ( root . data ) NEW_LINE printBoundaryLeft ( root . right ) NEW_LINE DEDENT DEDENT DEDENT def printBoundaryRight ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT if ( root . right ) : NEW_LINE INDENT printBoundaryRight ( root . right ) NEW_LINE print ( root . data ) NEW_LINE DEDENT elif ( root . left ) : NEW_LINE INDENT printBoundaryRight ( root . left ) NEW_LINE print ( root . data ) NEW_LINE DEDENT DEDENT DEDENT def printBoundary ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT print ( root . data ) NEW_LINE printBoundaryLeft ( root . left ) NEW_LINE printLeaves ( root . left ) NEW_LINE printLeaves ( root . right ) NEW_LINE printBoundaryRight ( root . right ) NEW_LINE DEDENT DEDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE printBoundary ( root ) NEW_LINE