Tree Traversals ( Inorder , Preorder and Postorder ) | A class that represents an individual node in a Binary Tree ; A function to do postorder tree traversal ; First recur on left child ; the recur on right child ; now print the data of node ; A function to do inorder tree traversal ; First recur on left child ; then print the data of node ; now recur on right child ; A function to do preorder tree traversal ; First print the data of node ; Then recur on left child ; Finally recur on right child ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = key NEW_LINE DEDENT DEDENT def printPostorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT printPostorder ( root . left ) NEW_LINE printPostorder ( root . right ) NEW_LINE print ( root . val ) , NEW_LINE DEDENT DEDENT def printInorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT printInorder ( root . left ) NEW_LINE print ( root . val ) , NEW_LINE printInorder ( root . right ) NEW_LINE DEDENT DEDENT def printPreorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT print ( root . val ) , NEW_LINE printPreorder ( root . left ) NEW_LINE printPreorder ( root . right ) NEW_LINE DEDENT DEDENT 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 . left . right = Node ( 5 ) NEW_LINE print " Preorder ▁ traversal ▁ of ▁ binary ▁ tree ▁ is " NEW_LINE printPreorder ( root ) NEW_LINE print   " NEW_LINE Inorder traversal of binary tree is " NEW_LINE printInorder ( root ) NEW_LINE print   " NEW_LINE Postorder traversal of binary tree is " NEW_LINE printPostorder ( root ) NEW_LINE