Search in a Binary Search Tree

easy

Given the root of a binary search tree and an integer val, return the subtree rooted at the node whose value equals val. If no such node exists, return null (an empty tree).

The tree is given/returned in level-order (breadth-first), using null for missing children.

Hints

In a BST, compare val to the node to decide the direction.
Smaller means the target is in the left subtree; larger means the right.
Walk straight down until you match or hit null — O(height).

Common doubts

The BST invariant guarantees the value can only be on one side, so exploring both wastes the ordering and makes it O(n).
The subtree rooted at the matching node, so callers can keep working within it.
On a degenerate (chain-like) BST the height is O(n); balancing keeps it O(log n).

Interview follow-ups

Search the same way; the null slot where the search ends is exactly where the new node goes.
Do the same descent but remember the best candidate seen so far on the correct side.

Fun facts

  • BST search is binary search on a tree — the same halving, but following pointers instead of array indices.
  • The path the search takes is exactly where an insert of that value would land.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: root = [4, 2, 7, 1, 3], val = 2
Output: [2, 1, 3]
2 is the left child of the root; return its whole subtree.
Example 2
Input: root = [4, 2, 7, 1, 3], val = 5
Output: []
5 is not in the tree.
Constraints

- The number of nodes is in the range [1, 5000] - 1 <= Node.val <= 10^7 - root is a valid BST - 1 <= val <= 10^7

Solve this problem →