Search in a Binary Search Tree


Link: LeetCode - Search in a Binary Search Tree

Problem Statement

Given the root of a binary search tree (BST) and an integer value, return the subtree rooted with the node that has the given value. If such a node does not exist, return null.


Intuition

A Binary Search Tree (BST) follows these properties:

So at each node:


Approach: Recursive Traversal

Use recursion based on the comparison between val and the current node’s value.


Java Code

class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        // Base Case: Tree is empty or the value is found
        if (root == null || root.val == val) {
            return root;
        }

        // Recursive Case
        if (val < root.val) {
            return searchBST(root.left, val);  // Search left subtree
        } else {
            return searchBST(root.right, val); // Search right subtree
        }
    }
}

Time and Space Complexity


Dry Run

Input Tree:

      4
     / \
    2   7
   / \
  1   3

val = 2

Output:

    2
   / \
  1   3

Conclusion

This problem demonstrates how efficiently we can search in a BST using its properties. Recursive traversal ensures we skip irrelevant subtrees and keep the solution optimal.