Skip to content
Decoder

Search in a Binary Search Tree

Easy

Problem

You are given the root of a binary search tree (every node is larger than everything in its left subtree and smaller than everything in its right subtree) and a value val.

Find the node whose value equals val and return the subtree rooted at that node. If no node has that value, return None (null in TypeScript).

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

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
null

Constraints

  • 1 <= number of nodes <= 5000
  • 1 <= Node.val <= 10^7
  • root is a valid binary search tree.
  • 1 <= val <= 10^7

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.