Iterative Preorder Traversal | Tree Node ; Iterative function to do Preorder traversal of the tree ; start from root node ( set current node to root node ) ; run till stack is not empty or current is not NULL ; Print left children while exist and keep appending right into the stack . ; We reach when curr is NULL , so We take out a right child from stack ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , data = 0 ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def preorderIterative ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT st = [ ] NEW_LINE curr = root NEW_LINE while ( len ( st ) or curr != None ) : NEW_LINE INDENT while ( curr != None ) : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE if ( curr . right != None ) : NEW_LINE INDENT st . append ( curr . right ) NEW_LINE DEDENT curr = curr . left NEW_LINE DEDENT if ( len ( st ) > 0 ) : NEW_LINE INDENT curr = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE DEDENT DEDENT DEDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 20 ) NEW_LINE root . right = Node ( 30 ) NEW_LINE root . left . left = Node ( 40 ) NEW_LINE root . left . left . left = Node ( 70 ) NEW_LINE root . left . right = Node ( 50 ) NEW_LINE root . right . left = Node ( 60 ) NEW_LINE root . left . left . right = Node ( 80 ) NEW_LINE preorderIterative ( root ) NEW_LINE