VOOZH about

URL: https://www.geeksforgeeks.org/dsa/search-n-elements-in-an-unbalanced-binary-search-tree-in-on-logm-time/

⇱ Search N elements in an unbalanced Binary Search Tree in O(N * logM) time - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

👁 Image
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.


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.

Related Articles:

Comment