Inorder Tree Traversal without Recursion | A binary tree node ; Iterative function for inorder tree traversal ; traverse the tree ; Reach the left most Node of the current Node ; Place pointer to a tree node on the stack before traversing the node 's left subtree ; BackTrack from the empty subtree and visit the Node at the top of the stack ; however , if the stack is empty you are done ; We have visited the node and its left subtree . Now , it ' s ▁ right ▁ subtree ' s turn ; Constructed binary tree is 1 / \ 2 3 / \ 4 5
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 inOrder ( root ) : NEW_LINE INDENT current = root NEW_LINE stack = [ ] NEW_LINE done = 0 NEW_LINE while True : NEW_LINE INDENT if current is not None : NEW_LINE INDENT stack . append ( current ) NEW_LINE current = current . left NEW_LINE DEDENT elif ( stack ) : NEW_LINE INDENT current = stack . pop ( ) NEW_LINE print ( current . data , end = " ▁ " ) NEW_LINE current = current . right NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE 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 inOrder ( root ) NEW_LINE