Skip to main content

Search in a Binary Search Tree

Problem Statement:​

You are given theΒ rootΒ of a binary search tree (BST) and an integerΒ val.

Find the node in the BST that the node's value equalsΒ valΒ and return the subtree rooted with that node. If such a node does not exist, returnΒ null.

Example 1:

Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]

Example 2:

Input: root = [4,2,7,1,3], val = 5
Output: []
  • Example:



class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
// Traverse the tree until you find the target value or reach NULL
while(root != NULL && root->val != val){
// Go left if val is smaller, right if greater
root = val < root->val ? root->left : root->right;
}
return root; // Found or NULL
}
};


class Solution {
public:
TreeNode *bst(TreeNode *root, int val){
if(root == NULL) return NULL;
if(root->val == val) return root;

// Recurse into left or right based on BST property
if(root->val < val) return bst(root->right, val);
else return bst(root->left, val);
}

TreeNode* searchBST(TreeNode* root, int val) {
return bst(root, val);
}
};


πŸ“ How It Works​

  • We take advantage of the BST property: for any node, all values in the left subtree are smaller, and all in the right are larger.
  • Iterative Version: Traverse using a loop, moving left or right based on comparison.
  • Recursive Version: Call recursively on the left or right subtree until you find the value or reach NULL.

🧩 Key Logic / Formula​

  • If val == root->val: return root.
  • If val < root->val: search in the left subtree.
  • If val > root->val: search in the right subtree.

⏱️ Time & Space Complexity​

ApproachTime ComplexitySpace Complexity
IterativeO(H)O(1) βœ…
RecursiveO(H)O(H) (stack)

Where H is the height of the tree β†’ O(log N) for balanced, O(N) for skewed trees.


⚠️ Edge Cases​

  • Tree is empty β†’ return NULL.
  • val does not exist in tree β†’ return NULL.
  • Tree has only one node.

πŸ’‘ Other Approaches​

ApproachSpaceNotes
RecursiveO(H)Simpler, uses call stack
IterativeO(1)More efficient in space βœ…

  • Leetcode 700
  • Insert into BST
  • Delete from BST
  • Lowest Common Ancestor in BST
  • Validate Binary Search Tree

πŸš€ Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Have handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contribute→