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
using System ; using System . Collections . Generic ; class GFG { public class node { public int data ; public node left ; public node right ; public 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 Queue < node > ( ) ; q . Enqueue ( root ) ; while ( q . Count > 0 ) { node node = q . Peek ( ) ; if ( node . data == x ) return true ; q . Dequeue ( ) ; if ( node . left != null ) q . Enqueue ( node . left ) ; if ( node . right != null ) q . Enqueue ( node . right ) ; } return false ; } public static void Main ( String [ ] ags ) { 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 ) ; Console . WriteLine ( ( iterativeSearch ( root , 6 ) ? " Found STRNEWLINE " : " Not ▁ Found " ) ) ; Console . Write ( ( iterativeSearch ( root , 12 ) ? " Found STRNEWLINE " : " Not ▁ Found STRNEWLINE " ) ) ; } }