InterviewPrepKit

Home / Coding / Trees

Search in a Binary Search Tree

easy Original ↗
Solving tips
  • Recognize this as binary search on a tree: one comparison at each node discards an entire subtree, exploiting the BST order.
  • Compare val to node.val: equal returns the node, smaller goes left, larger goes right; falling off returns None.
  • Since the recursion is tail-recursive, unroll it into a while-loop with a moving pointer for O(1) space; O(h) time.
  • Say O(h), not O(log n): a skewed BST degrades to a linked list, and never search both subtrees 'to be safe'.

Problem

You are given the root of a binary search tree (BST) and an integer val. Find the node whose value equals val and return the subtree rooted at that node. If no node has that value, return None.

Recall the BST property: for every node, all values in its left subtree are smaller than the node’s value, and all values in its right subtree are larger. All values in the tree are distinct.

Examples

Example 1

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

Node 2 is the root’s left child; the returned subtree is node 2 with children 1 and 3.

Example 2

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

5 is not in the tree (we’d go left from 7, which has no left child), so the answer is None.

Example 3

Input: root = [8,3,10,1,6], val = 8
Output: [8,3,10,1,6]

The target is the root itself, so the whole tree is returned.

Constraints

  • The number of nodes is in the range [1, 5000].
  • 1 <= Node.val <= 10^7, all values unique.
  • 1 <= val <= 10^7
  • The tree is guaranteed to be a valid BST.

The BST guarantee is the whole point: the expected solution visits one node per level, not every node.

Think about it first

Hint 1 If you ignore the BST property, how would you find the value? Now ask: what does the BST property let you skip?
Hint 2 Compare `val` with the current node's value. If they differ, exactly one subtree can possibly contain `val` — which one?
Hint 3 It's binary search on a tree: equal → return the node; `val` smaller → recurse (or step) left; `val` larger → go right; fell off the tree → return None.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.