Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Last Updated : 23 Jul, 2025
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time.
Examples:
Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree
BST
Output: Found Not Found Found Found Found Found Not Found
Naive Approach:
For each element, we will try to search for that element in the BST.
Time Complexity: O(N * M) as the tree is not balanced the height may become M. In that case, the overall complexity of searching will become O(N * M) Auxiliary Space: O(1)
Efficient Approach: The operations can be performed efficiently by following the below idea:
First store the In-Order Traversals in an array and using binary search for searching the elements in that array because the inorder traversal of the BST will always give a sorted array.
Follow the below steps to solve the problem:
Do a inorder traversal of the BST. i.e. O(M) time.
Store the in-order traversal in the array.
The array is sorted. As the inorder traversal of BST is in a sorted fashion.
As it is Left Root Right. All Left elements are smaller than the root, all right elements are larger than root.
Now simply use the binary search in the array.
Return the answer.
Below is the Implementation of the above approach.
C++
// C++ code to implement the approach#include<bits/stdc++.h>usingnamespacestd;// BST nodestructTreeNode{intval;structTreeNode*left,*right;};// Build a new nodeTreeNode*newNode(intdata){TreeNode*temp=newTreeNode;temp->val=data;temp->left=NULL;temp->right=NULL;returntemp;}// Function to insert a new nodeTreeNode*insert(TreeNode*root,intval){TreeNode*newnode=newNode(val);TreeNode*x=root;TreeNode*y=NULL;while(x!=NULL){y=x;if(val<x->val)x=x->left;elsex=x->right;}if(y==NULL)y=newnode;elseif(val<y->val)y->left=newnode;elsey->right=newnode;returny;}// Function for performing inorder traversal of BSTvoidinorder(vector<int>&inord,TreeNode*root){if(root==NULL){return;}inorder(inord,root->left);inord.push_back(root->val);inorder(inord,root->right);}// Function to search a element in the BSTboolBSTSearch(vector<int>&inord,inttarget){returnbinary_search(inord.begin(),inord.end(),target);}voidprintArr(intN,vector<int>&targets,vector<int>&inorder){for(inti=0;i<N;i++){if(BSTSearch(inorder,targets[i]))cout<<"Found"<<"\n";elsecout<<"Not Found"<<"\n";}}// Driver codeintmain(){TreeNode*root=NULL;root=insert(root,8);insert(root,15);insert(root,4);insert(root,7);insert(root,1);insert(root,6);insert(root,5);// BST Inorder - sorted arrayvector<int>inor;inorder(inor,root);vector<int>targets={6,2,7,4,5,1,3};intN=targets.size();printArr(N,targets,inor);return0;}
Java
// Java code to implement the approachimportjava.io.*;importjava.util.*;// BST nodeclassTreeNode{intval;TreeNodeleft,right;}classGFG{// Build a new nodestaticTreeNodenewNode(intdata){TreeNodetemp=newTreeNode();temp.val=data;temp.left=null;temp.right=null;returntemp;}// Function to insert a new nodestaticTreeNodeinsert(TreeNoderoot,intval){TreeNodenewnode=newNode(val);TreeNodex=root;TreeNodey=null;while(x!=null){y=x;if(val<x.val){x=x.left;}else{x=x.right;}}if(y==null){y=newnode;}elseif(val<y.val){y.left=newnode;}else{y.right=newnode;}returny;}// Function for performing inorder traversal of BSTstaticvoidinorder(List<Integer>inord,TreeNoderoot){if(root==null){return;}inorder(inord,root.left);inord.add(root.val);inorder(inord,root.right);}// Function to search a element in the BSTstaticbooleanBSTSearch(List<Integer>inord,inttarget){returninord.contains(target);}staticvoidprintArr(intN,int[]targets,List<Integer>inorder){for(inti=0;i<N;i++){if(BSTSearch(inorder,targets[i])){System.out.println("Found");}else{System.out.println("Not Found");}}}publicstaticvoidmain(String[]args){TreeNoderoot=null;root=insert(root,8);insert(root,15);insert(root,4);insert(root,7);insert(root,1);insert(root,6);insert(root,5);// BST Inorder - sorted arrayList<Integer>inor=newArrayList<>();inorder(inor,root);int[]targets={6,2,7,4,5,1,3};intN=targets.length;printArr(N,targets,inor);}}// This code is contributed by lokeshmvs21.
Python3
# Python code to implement the approach# Binary tree nodeclassTreeNode:# Constructor to create a new nodedef__init__(self,val):self.val=valself.left=Noneself.right=None# Function to insert a new nodedefinsert(root,val):newnode=TreeNode(val)x=rooty=Nonewhilex!=None:y=xifval<x.val:x=x.leftelse:x=x.rightify==None:y=newnodeelifval<y.val:y.left=newnodeelse:y.right=newnodereturny# Function for performing inorder traversal of BSTdefinorder(inord,root):ifroot==None:returninorder(inord,root.left)inord.append(root.val)inorder(inord,root.right)# Function to search an element in the BSTdefBSTSearch(inord,target):returntargetininorddefprintArr(N,targets,inorder):foriinrange(N):ifBSTSearch(inorder,targets[i]):print("Found")else:print("Not Found")# Driver coderoot=Noneroot=insert(root,8)insert(root,15)insert(root,4)insert(root,7)insert(root,1)insert(root,6)insert(root,5)# BST Inorder - sorted arrayinor=[]inorder(inor,root)targets=[6,2,7,4,5,1,3]N=len(targets)printArr(N,targets,inor)# This code os contributed by ksam24000
C#
// C# code to implement the approachusingSystem;usingSystem.Collections.Generic;// BST nodeclassTreeNode{publicintval;publicTreeNodeleft,right;}classGFG{// Build a new nodestaticTreeNodeNewNode(intdata){TreeNodetemp=newTreeNode();temp.val=data;temp.left=null;temp.right=null;returntemp;}// Function to insert a new nodestaticTreeNodeInsert(TreeNoderoot,intval){TreeNodenewnode=NewNode(val);TreeNodex=root;TreeNodey=null;while(x!=null){y=x;if(val<x.val){x=x.left;}else{x=x.right;}}if(y==null){y=newnode;}elseif(val<y.val){y.left=newnode;}else{y.right=newnode;}returny;}// Function for performing inorder traversal of BSTstaticvoidInorder(List<int>inord,TreeNoderoot){if(root==null){return;}Inorder(inord,root.left);inord.Add(root.val);Inorder(inord,root.right);}// Function to search a element in the BSTstaticboolBSTSearch(List<int>inord,inttarget){returninord.Contains(target);}staticvoidPrintArr(intN,int[]targets,List<int>inorder){for(inti=0;i<N;i++){if(BSTSearch(inorder,targets[i])){Console.WriteLine("Found");}else{Console.WriteLine("Not Found");}}}staticvoidMain(string[]args){TreeNoderoot=null;root=Insert(root,8);Insert(root,15);Insert(root,4);Insert(root,7);Insert(root,1);Insert(root,6);Insert(root,5);// BST Inorder - sorted arrayList<int>inor=newList<int>();Inorder(inor,root);int[]targets={6,2,7,4,5,1,3};intN=targets.Length;PrintArr(N,targets,inor);}}// This code is contributed by lokesh.
JavaScript
// JavaScript code implementationclassTreeNode{constructor(val){this.val=val;this.left=null;this.right=null;}}functionnewNode(data){consttemp=newTreeNode(data);returntemp;}functioninsert(root,val){constnewnode=newNode(val);letx=root;lety=null;while(x!==null){y=x;if(val<x.val)x=x.left;elsex=x.right;}if(y===null)y=newnode;elseif(val<y.val)y.left=newnode;elsey.right=newnode;returny;}functioninorder(inord,root){if(root===null)return;inorder(inord,root.left);inord.push(root.val);inorder(inord,root.right);}functionBSTSearch(inord,target){returninord.includes(target);}functionprintArr(N,targets,inorder){for(leti=0;i<N;i++){if(BSTSearch(inorder,targets[i]))console.log('Found');elseconsole.log('Not Found');}}constroot=newTreeNode(null);insert(root,8);insert(root,15);insert(root,4);insert(root,7);insert(root,1);insert(root,6);insert(root,5);constinor=[];inorder(inor,root);consttargets=[6,2,7,4,5,1,3];constN=targets.length;printArr(N,targets,inor);// This code is contributed by ksam24000
Output
Found
Not Found
Found
Found
Found
Found
Not Found
Time Complexity : O(M + N * log M)
In-order traversal takes O(M) for once
BST Search is now optimized to O(log M) always irrespective of the height of BST.
Auxiliary Space: O(M), The In-order traversal needs to be stored in arrays.