Iterative Search for a key ' x ' in Binary Tree | Iterative level order traversal based method to search in Binary Tree ; A binary tree node has data , left child and right child ; Constructor that allocates a new node with the given data and null left and right pointers . ; An iterative process to search an element x in a given binary tree ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; Queue based level order traversal ; See if current node is same as x ; Remove current node and enqueue its children ; Driver code
import java . util . * ; class GFG { static class node { int data ; node left ; node right ; node ( int data ) { this . data = data ; this . left = null ; this . right = null ; } } ; static boolean iterativeSearch ( node root , int x ) { if ( root == null ) return false ; Queue < node > q = new LinkedList ( ) ; q . add ( root ) ; while ( q . size ( ) > 0 ) { node node = q . peek ( ) ; if ( node . data == x ) return true ; q . remove ( ) ; if ( node . left != null ) q . add ( node . left ) ; if ( node . right != null ) q . add ( node . right ) ; } return false ; } public static void main ( String ags [ ] ) { node NewRoot = null ; node root = new node ( 2 ) ; root . left = new node ( 7 ) ; root . right = new node ( 5 ) ; root . left . right = new node ( 6 ) ; root . left . right . left = new node ( 1 ) ; root . left . right . right = new node ( 11 ) ; root . right . right = new node ( 9 ) ; root . right . right . left = new node ( 4 ) ; System . out . print ( ( iterativeSearch ( root , 6 ) ? "Found " : ▁ " Not Found "));  System . out . print ( ( iterativeSearch ( root , 12 ) ? "Found " : ▁ " Not Found "));  } }