Iterative Preorder Traversal | A binary tree node ; An iterative process to print preorder traveral of BT ; Base CAse ; create an empty stack and push root to it ; Pop all items one by one . Do following for every popped item a ) print it b ) push its right child c ) push its left child Note that right child is pushed first so that left is processed first ; Pop the top item from stack and print it ; Push right and left children of the popped node to stack ; 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 iterativePreorder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT nodeStack = [ ] NEW_LINE nodeStack . append ( root ) NEW_LINE while ( len ( nodeStack ) > 0 ) : NEW_LINE INDENT node = nodeStack . pop ( ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE if node . right is not None : NEW_LINE INDENT nodeStack . append ( node . right ) NEW_LINE DEDENT if node . left is not None : NEW_LINE INDENT nodeStack . append ( node . left ) NEW_LINE DEDENT DEDENT DEDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 2 ) NEW_LINE root . left . left = Node ( 3 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 2 ) NEW_LINE iterativePreorder ( root ) NEW_LINE