AlgoFrames

Search

Standard · Write code · about 8 min

Given the root of a binary search tree and a val, find the node whose value equals val and return the subtree rooted at it. Return null if there is no such node.

Example 1

Input:

[[4,2,7,1,3],2]

Output:

[2,1,3]

The tree is shown in level order.

Example 2

Input:

[[4,2,7,1,3],5]

Output:

null

5 is not in the tree.

Constraints

  • 0 ≤ number of nodes ≤ 1,000
  • Keys are distinct integers with -1,000 ≤ key ≤ 1,000
  • The tree is a valid BST, given in level order; null marks a missing child

Learn the idea first: BST: search, insert, min and max, a visual lesson.

More BST: search, insert, min and max problems