Search an element in binary tree without recursion.
💻 coding

Search an element in binary tree without recursion.

1 min read 208 words
1 min read
ShareWhatsAppPost on X
  • 1Level order traversal can be adapted to search for an element in a binary tree without using recursion.
  • 2The search process involves checking each node's data against the target element during traversal.
  • 3The time complexity of this method is O(n), while the space complexity is also O(n) due to the queue.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Level order traversal can be adapted to search for an element in a binary tree without using recursion."

Search an element in binary tree without recursion.

We can use level order traversal for solving this problem. The only change required in level order traversal is, instead of printing the date we just need to check whether the root data is equal to the element we want to search.

source: Data Structures and Algorithms Made Easy in Java ( By Narasimha Karumanchi )

Java implementation is as below:

package askgif.tree;

import java.util.LinkedList;
import java.util.Queue;

class Node
{
 int data;
 Node left, right;
 
 public Node(int item)
 {
 data = item;
 left = right = null;
 }
}

class BinaryTree
{
 Node root;
 
 BinaryTree()
 {
 root = null;
 }
 
}

public class TreeQuestions {

	public static void main(String[] args) {
		BinaryTree binaryTree = new BinaryTree();
		Node root = new Node(1);
		binaryTree.root = root;
		binaryTree.root.left = new Node(2);
		binaryTree.root.right = new Node(3);
		
		binaryTree.root.left.left = new Node(4);
		binaryTree.root.left.right = new Node(5);
 
		int data = 4;
 System.out.println(SearchUsingLevelOrder(root, data));

	}

	private static Boolean SearchUsingLevelOrder(Node treeNode, int data) {
		if(treeNode == null)
			return false;
		
		Queue<Node> queue = new LinkedList<Node>();
		queue.add(treeNode);
		
		while(!queue.isEmpty()) {
			Node temp = queue.remove();
			if(temp.data == data)
				return true;
			if(temp.left != null)
				queue.add(temp.left);
			if(temp.right != null)
				queue.add(temp.right);
		}
		
		return false;
	}

}
output:

true

Time Complexity: O(n) for traversing each node

Space Complexity: O(n) for storing elements in a queue.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 16 August 2018 · 1 min read · 208 words

Part of AskGif Blog · coding

You might also like

Search an element in binary tree without recursion. | AskGif Blog