VOOZH about

URL: https://www.geeksforgeeks.org/dsa/binary-search-tree-set-1-search-and-insertion/

⇱ Searching in Binary Search Tree (BST) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Searching in Binary Search Tree (BST)

Last Updated : 13 Oct, 2025

Given the root of a Binary Search Tree and a value key, find if key is present in the BST or not.

Note: The key may or may not be present in the BST.

Input: key = 7

👁 420046703

Output: true
Explanation: 7 is present in the BST.

Input: key = 14

👁 420046702

Output: false
Explanation: 14 is not present in the BST.

How to search a value in Binary Search Tree:

Let's say we want to search for the number key, We start at the root. Then:

  • We compare the value to be searched with the value of the root. 
  • If it's equal we are done with the search.
  • If it's smaller we know that we need to go to the left subtree.
  • If it's greater we search in the right subtree. 
  • Repeat the above step till no more traversal is possible
  • If at any iteration, key is found, return True. If the node is null, return False.

Illustration of searching a key in BST:

See the illustration below for a better understanding:


Searching in Binary Search Tree using Recursion:


Output
1

Time complexity: O(h), where h is the height of the BST.
Auxiliary Space: O(h) This is because of the space needed to store the recursion stack.

We can avoid the auxiliary space and recursion overhead withe help of iterative implementation. Below is the iterative implementation that works in O(h) time and O(1) auxiliary space.

Searching in Binary Search Tree using Iterative approach:


Output
1

Time complexity: O(h), where h is the height of the BST.
Auxiliary Space: O(1)

Comment