Iterative Search for a key ' x ' in Binary Tree | A binary tree node has data , left child and right child ; Construct to create a newNode ; iterative process to search an element x in a given binary tree ; Base Case ; Create an empty stack and append root to it ; Do iterative preorder traversal to search x ; See the top item from stack and check if it is same as x ; append right and left children of the popped node to stack ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def iterativeSearch ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT nodeStack = [ ] NEW_LINE nodeStack . append ( root ) NEW_LINE while ( len ( nodeStack ) ) : NEW_LINE INDENT node = nodeStack [ 0 ] NEW_LINE if ( node . data == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT nodeStack . pop ( 0 ) NEW_LINE if ( node . right ) : NEW_LINE INDENT nodeStack . append ( node . right ) NEW_LINE DEDENT if ( node . left ) : NEW_LINE INDENT nodeStack . append ( node . left ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 7 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 1 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . right = newNode ( 9 ) NEW_LINE root . right . right . left = newNode ( 4 ) NEW_LINE if iterativeSearch ( root , 6 ) : NEW_LINE INDENT print ( " Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Found " ) NEW_LINE DEDENT if iterativeSearch ( root , 12 ) : NEW_LINE INDENT print ( " Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Found " ) NEW_LINE DEDENT