Iterative Search for a key ‘x’ in Binary Tree
Last Updated :
10 Mar, 2023
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.
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.
- Iterative Level Order Traversal.
- Iterative Inorder Traversal
- Iterative Preorder Traversal
- Iterative Postorder Traversal
Below is iterative Level Order Traversal based solution to search an item x in binary tree.
C++
#include<bits/stdc++.h>
using namespace std;
class node
{
public :
int data;
node* left;
node* right;
node( int data){
this ->data = data;
this ->left = NULL;
this ->right = NULL;
}
};
bool iterativeSearch(node *root, int x)
{
if (root == NULL)
return false ;
queue<node *> q;
q.push(root);
while (q.empty() == false )
{
node *node = q.front();
if (node->data == x)
return true ;
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
return false ;
}
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\n" : cout << "Not Found\n" ;
iterativeSearch(root, 12)? cout <<
"Found\n" : cout << "Not Found\n" ;
return 0;
}
|
C
#include <iostream>
#include <queue>
using namespace std;
struct node
{
int data;
struct node* left, *right;
};
struct node* newNode( int data)
{
struct node* node = new struct node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
bool iterativeSearch(node *root, int x)
{
if (root == NULL)
return false ;
queue<node *> q;
q.push(root);
while (q.empty() == false )
{
node *node = q.front();
if (node->data == x)
return true ;
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
return false ;
}
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\n" : cout << "Not Found\n" ;
iterativeSearch(root, 12)? cout << "Found\n" : cout << "Not Found\n" ;
return 0;
}
|
Java
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\n" : "Not Found\n" ));
System.out.print((iterativeSearch(root, 12 )?
"Found\n" : "Not Found\n" ));
}
}
|
Python3
from queue import Queue
class newNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def iterativeSearch(root, x):
if (root = = None ):
return False
q = Queue()
q.put(root)
while (q.empty() = = False ):
node = q.queue[ 0 ]
if (node.data = = x):
return True
q.get()
if (node.left ! = None ):
q.put(node.left)
if (node.right ! = None ):
q.put(node.right)
return False
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" )
|
C#
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\n" :
"Not Found" ));
Console.Write((iterativeSearch(root, 12) ?
"Found\n" :
"Not Found\n" ));
}
}
|
Javascript
<script>
class node
{
constructor(data)
{
this .data = data;
this .left = null ;
this .right = null ;
}
}
function iterativeSearch(root,x)
{
if (root == null )
return false ;
let q = [];
q.push(root);
while (q.length > 0)
{
let node = q[0];
if (node.data == x)
return true ;
q.shift();
if (node.left != null )
q.push(node.left);
if (node.right != null )
q.push(node.right);
}
return false ;
}
let NewRoot = null ;
let 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);
document.write((iterativeSearch(root, 6)?
"Found<br>" : "Not Found<br>" ));
document.write((iterativeSearch(root, 12)?
"Found<br>" : "Not Found<br>" ));
</script>
|
Time Complexity: O(N), where N is number of nodes as every node of Binary Tree.
Auxiliary Space: O(N)
Below implementation uses Iterative Preorder Traversal to find x in Binary Tree
C++
#include <iostream>
#include <stack>
using namespace std;
struct node
{
int data;
struct node* left, *right;
};
struct node* newNode( int data)
{
struct node* node = new struct node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
bool iterativeSearch(node *root, int x)
{
if (root == NULL)
return false ;
stack<node *> nodeStack;
nodeStack.push(root);
while (nodeStack.empty() == false )
{
struct node *node = nodeStack.top();
if (node->data == x)
return true ;
nodeStack.pop();
if (node->right)
nodeStack.push(node->right);
if (node->left)
nodeStack.push(node->left);
}
return false ;
}
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\n" : cout << "Not Found\n" ;
iterativeSearch(root, 12)? cout << "Found\n" : cout << "Not Found\n" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class node
{
int data;
node left, right;
};
static node newNode( int data)
{
node node = new node();
node.data = data;
node.left = node.right = null ;
return (node);
}
static boolean iterativeSearch(node root, int x)
{
if (root == null )
return false ;
Stack<node> nodeStack = new Stack<node>();
nodeStack.push(root);
while (nodeStack.empty() == false )
{
node node = nodeStack.peek();
if (node.data == x)
return true ;
nodeStack.pop();
if (node.right != null )
nodeStack.push(node.right);
if (node.left != null )
nodeStack.push(node.left);
}
return false ;
}
public static void main(String[] args)
{
node NewRoot = null ;
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 );
if (iterativeSearch(root, 6 ))
System.out.println( "Found" );
else
System.out.println( "Not Found" );
if (iterativeSearch(root, 12 ))
System.out.println( "Found" );
else
System.out.println( "Not Found" );
}
}
|
Python3
class newNode:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def iterativeSearch(root,x):
if (root = = None ):
return False
nodeStack = []
nodeStack.append(root)
while ( len (nodeStack)):
node = nodeStack[ 0 ]
if (node.data = = x):
return True
nodeStack.pop( 0 )
if (node.right):
nodeStack.append(node.right)
if (node.left):
nodeStack.append(node.left)
return False
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" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
class node
{
public int data;
public node left, right;
};
static node newNode( int data)
{
node node = new node();
node.data = data;
node.left = node.right = null ;
return (node);
}
static bool iterativeSearch(node root, int x)
{
if (root == null )
return false ;
Stack<node> nodeStack = new Stack<node>();
nodeStack.Push(root);
while (nodeStack.Count != 0)
{
node node = nodeStack.Peek();
if (node.data == x)
return true ;
nodeStack.Pop();
if (node.right != null )
nodeStack.Push(node.right);
if (node.left != null )
nodeStack.Push(node.left);
}
return false ;
}
public static void Main(String[] args)
{
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);
if (iterativeSearch(root, 6))
Console.WriteLine( "Found" );
else
Console.WriteLine( "Not Found" );
if (iterativeSearch(root, 12))
Console.WriteLine( "Found" );
else
Console.WriteLine( "Not Found" );
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .data = 0;
this .left = null ;
this .right = null ;
}
};
function newNode(data)
{
var node = new Node();
node.data = data;
node.left = node.right = null ;
return (node);
}
function iterativeSearch(root, x)
{
if (root == null )
return false ;
var nodeStack = [];
nodeStack.push(root);
while (nodeStack.length != 0)
{
var node = nodeStack[nodeStack.length - 1];
if (node.data == x)
return true ;
nodeStack.pop();
if (node.right != null )
nodeStack.push(node.right);
if (node.left != null )
nodeStack.push(node.left);
}
return false ;
}
var 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))
document.write( "Found<br>" );
else
document.write( "Not Found<br>" );
if (iterativeSearch(root, 12))
document.write( "Found<br>" );
else
document.write( "Not Found<br>" );
</script>
|
Time Complexity: O(N), where N is number of nodes as every node of Binary Tree.
Auxiliary Space: O(h) where h is the height of the tree.
Similarly, Iterative Inorder and Iterative Postorder traversals can be used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...