InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Search in a Binary Search Tree

easy Original ↗ 00:00

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.

Because the tree is a valid BST, 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 This is binary search on a tree: equal → return the node; `val` smaller → go left; `val` larger → go right; reached `None` → return `None`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug