Search in a Binary Search Tree

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 holds `val`, return `null` (shown as `[]`).

30:00

Search in a Binary Search Tree
easy
Free written solution
Topics
Companies

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 holds val, return null (shown as []).

Example 1:
Input: {"root":[4,2,7,1,3],"val":2}
Output: [2,1,3]
Constraints:
  • The number of nodes in the tree is in the range [1,5000][1, 5000].

  • 1≤Node.val≤1071 \leq \text{Node.val} \leq 10^7

  • root is a binary search tree.

  • 1≤val≤1071 \leq \text{val} \leq 10^7

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[4,2,7,1,3],"val":2}

Look for 2. In sorted order every one of the 5 values is still a candidate.

val = 2
candidates: 5 / 5
moves: 0
42713

Same values in sorted order (in-order). Each move throws away one side.

12347
root (current)
path taken
still possible
returned subtree
fell off: null
Variables
VariableValue
val2
root4
candidates5
DepthFunction Call
Stack empty
0/4