# Iterative Search for a key ‘x’ in Binary Tree

Given a Binary Tree and a key to be searched in it, write an iterative method that returns true if key is present in Binary Tree, else false.

For example, in the following tree, if the searched key is 3, then function should return true and if the searched key is 12, then function should return false. ## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

One thing is sure that we need to traverse complete tree to decide whether key is present or not. We can use any of the following traversals to iteratively search a key in a given binary tree.
1) Iterative Level Order Traversal.
2) Iterative Inorder Traversal
3) Iterative Preorder Traversal
4) Iterative Postorder Traversal

Below is iterative Level Order Traversal based solution to search an item x in binary tree.

## C++

 `// Iterative level order traversal ` `// based method to search in Binary Tree  ` `#include  ` `#include ` `using` `namespace` `std;  ` ` `  `/* A binary tree node has data, ` `left child and right child */` `class` `node  ` `{  ` `    ``public``: ` `    ``int` `data;  ` `    ``node* left;  ` `    ``node* right;  ` `     `  `    ``/* Constructor that allocates a new node with the  ` `    ``given data and NULL left and right pointers. */` `    ``node(``int` `data){ ` `        ``this``->data = data; ` `        ``this``->left = NULL; ` `        ``this``->right = NULL; ` `         `  `    ``} ` `};  ` ` `  ` `  `// An iterative process to search ` `// an element x in a given binary tree  ` `bool` `iterativeSearch(node *root, ``int` `x)  ` `{  ` `    ``// Base Case  ` `    ``if` `(root == NULL)  ` `        ``return` `false``;  ` ` `  `    ``// Create an empty queue for  ` `    ``// level order traversal  ` `    ``queue q;  ` ` `  `    ``// Enqueue Root and initialize height  ` `    ``q.push(root);  ` ` `  `    ``// Queue based level order traversal  ` `    ``while` `(q.empty() == ``false``)  ` `    ``{  ` `        ``// See if current node is same as x  ` `        ``node *node = q.front();  ` `        ``if` `(node->data == x)  ` `            ``return` `true``;  ` ` `  `        ``// Remove current node and enqueue its children  ` `        ``q.pop();  ` `        ``if` `(node->left != NULL)  ` `            ``q.push(node->left);  ` `        ``if` `(node->right != NULL)  ` `            ``q.push(node->right);  ` `    ``}  ` ` `  `    ``return` `false``;  ` `}  ` ` `  `// Driver code  ` `int` `main()  ` `{  ` `    ``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);  ` ` `  `    ``iterativeSearch(root, 6)? cout <<  ` `    ````"Found "````: cout << ````"Not Found "````;  ` `    ``iterativeSearch(root, 12)? cout <<  ` `    ````"Found "````: cout << ````"Not Found "````;  ` `    ``return` `0;  ` `} ` ` `  `// This code is contributed by rathbhupendra `

## C

 `// Iterative level order traversal based method to search in Binary Tree ` `#include ` `#include ` `using` `namespace` `std; ` ` `  `/* A binary tree node has data, left child and right child */` `struct` `node ` `{ ` `    ``int` `data; ` `    ``struct` `node* left, *right; ` `}; ` ` `  `/* Helper function that allocates a new node with the given data and ` `   ``NULL left and right  pointers.*/` `struct` `node* newNode(``int` `data) ` `{ ` `    ``struct` `node* node = ``new` `struct` `node; ` `    ``node->data = data; ` `    ``node->left = node->right = NULL; ` `    ``return``(node); ` `} ` ` `  `// An iterative process to search an element x in a given binary tree ` `bool` `iterativeSearch(node *root, ``int` `x) ` `{ ` `    ``// Base Case ` `    ``if` `(root == NULL) ` `        ``return` `false``; ` ` `  `    ``// Create an empty queue for level order traversal ` `    ``queue q; ` ` `  `    ``// Enqueue Root and initialize height ` `    ``q.push(root); ` ` `  `    ``// Queue based level order traversal ` `    ``while` `(q.empty() == ``false``) ` `    ``{ ` `        ``// See if current node is same as x ` `        ``node *node = q.front(); ` `        ``if` `(node->data == x) ` `            ``return` `true``; ` ` `  `        ``// Remove current node and enqueue its children ` `        ``q.pop(); ` `        ``if` `(node->left != NULL) ` `            ``q.push(node->left); ` `        ``if` `(node->right != NULL) ` `            ``q.push(node->right); ` `    ``} ` ` `  `    ``return` `false``; ` `} ` ` `  `// Driver program ` `int` `main(``void``) ` `{ ` `    ``struct` `node*NewRoot=NULL; ` `    ``struct` `node *root = newNode(2); ` `    ``root->left        = newNode(7); ` `    ``root->right       = newNode(5); ` `    ``root->left->right = newNode(6); ` `    ``root->left->right->left=newNode(1); ` `    ``root->left->right->right=newNode(11); ` `    ``root->right->right=newNode(9); ` `    ``root->right->right->left=newNode(4); ` ` `  `    ``iterativeSearch(root, 6)? cout << ````"Found "````: cout << ````"Not Found "````; ` `    ``iterativeSearch(root, 12)? cout << ````"Found "````: cout << ````"Not Found "````; ` `    ``return` `0; ` `} `

## Python3

 `# Iterative level order traversal based ` `# method to search in Binary Tree  ` ` `  `# importing Queue ` `from` `queue ``import` `Queue ` ` `  `# Helper function that allocates a  ` `# new node with the given data and  ` `# None left and right pointers. ` `class` `newNode: ` `    ``def` `__init__(``self``, data):  ` `        ``self``.data ``=` `data  ` `        ``self``.left ``=` `self``.right ``=` `None` ` `  `# An iterative process to search an ` `# element x in a given binary tree  ` `def` `iterativeSearch(root, x): ` `     `  `    ``# Base Case  ` `    ``if` `(root ``=``=` `None``): ` `        ``return` `False` ` `  `    ``# Create an empty queue for level ` `    ``# order traversal  ` `    ``q ``=` `Queue()  ` ` `  `    ``# Enqueue Root and initialize height  ` `    ``q.put(root)  ` ` `  `    ``# Queue based level order traversal  ` `    ``while` `(q.empty() ``=``=` `False``): ` `         `  `        ``# See if current node is same as x  ` `        ``node ``=` `q.queue[``0``]  ` `        ``if` `(node.data ``=``=` `x):  ` `            ``return` `True` ` `  `        ``# Remove current node and  ` `        ``# enqueue its children  ` `        ``q.get() ` `        ``if` `(node.left !``=` `None``): ` `            ``q.put(node.left)  ` `        ``if` `(node.right !``=` `None``): ` `            ``q.put(node.right) ` ` `  `    ``return` `False` ` `  `# Driver Code ` `if` `__name__ ``=``=` `'__main__'``: ` ` `  `    ``root ``=` `newNode(``2``)  ` `    ``root.left ``=` `newNode(``7``)  ` `    ``root.right ``=` `newNode(``5``)  ` `    ``root.left.right ``=` `newNode(``6``)  ` `    ``root.left.right.left ``=` `newNode(``1``)  ` `    ``root.left.right.right ``=` `newNode(``11``)  ` `    ``root.right.right ``=` `newNode(``9``)  ` `    ``root.right.right.left ``=` `newNode(``4``)  ` ` `  `    ``if` `iterativeSearch(root, ``6``): ` `        ``print``(``"Found"``) ` `    ``else``: ` `        ``print``(``"Not Found"``)  ` `    ``if` `iterativeSearch(root, ``12``): ` `        ``print``(``"Found"``) ` `    ``else``: ` `        ``print``(``"Not Found"``) ` ` `  `# This code is contributed by PranchalK `

Output:

```Found
Not Found```

Below implementation uses Iterative Preorder Traversal to find x in Binary Tree

 `// An iterative method to search an item in Binary Tree ` `#include ` `#include ` `using` `namespace` `std; ` ` `  `/* A binary tree node has data, left child and right child */` `struct` `node ` `{ ` `    ``int` `data; ` `    ``struct` `node* left, *right; ` `}; ` ` `  `/* Helper function that allocates a new node with the given data and ` `   ``NULL left and right  pointers.*/` `struct` `node* newNode(``int` `data) ` `{ ` `    ``struct` `node* node = ``new` `struct` `node; ` `    ``node->data = data; ` `    ``node->left = node->right = NULL; ` `    ``return``(node); ` `} ` ` `  `// iterative process to search an element x in a given binary tree ` `bool` `iterativeSearch(node *root, ``int` `x) ` `{ ` `    ``// Base Case ` `    ``if` `(root == NULL) ` `        ``return` `false``; ` ` `  `    ``// Create an empty stack and push root to it ` `    ``stack nodeStack; ` `    ``nodeStack.push(root); ` ` `  `    ``// Do iterative preorder traversal to search x ` `    ``while` `(nodeStack.empty() == ``false``) ` `    ``{ ` `        ``// See the top item from stack and check if it is same as x ` `        ``struct` `node *node = nodeStack.top(); ` `        ``if` `(node->data == x) ` `            ``return` `true``; ` `        ``nodeStack.pop(); ` ` `  `        ``// Push right and left children of the popped node to stack ` `        ``if` `(node->right) ` `            ``nodeStack.push(node->right); ` `        ``if` `(node->left) ` `            ``nodeStack.push(node->left); ` `    ``} ` ` `  `    ``return` `false``; ` `} ` ` `  `// Driver program ` `int` `main(``void``) ` `{ ` `    ``struct` `node*NewRoot=NULL; ` `    ``struct` `node *root = newNode(2); ` `    ``root->left        = newNode(7); ` `    ``root->right       = newNode(5); ` `    ``root->left->right = newNode(6); ` `    ``root->left->right->left=newNode(1); ` `    ``root->left->right->right=newNode(11); ` `    ``root->right->right=newNode(9); ` `    ``root->right->right->left=newNode(4); ` ` `  `    ``iterativeSearch(root, 6)? cout << ````"Found "````: cout << ````"Not Found "````; ` `    ``iterativeSearch(root, 12)? cout << ````"Found "````: cout << ````"Not Found "````; ` `    ``return` `0; ` `} `

Output:

```Found
Not Found```

Similarly, Iterative Inorder and Iterative Postorder traversals can be used.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

This article is attributed to GeeksforGeeks.org

Tree Tree

code

load comments