Ctrl K

Find the Subtree by Key

Easy
You are given root, the root of a binary search tree: for every node, all values in its left subtree are smaller than its own and all values in its right subtree are larger. All values are distinct. Find the node whose value is key and return it, which means returning the whole subtree that grows from it. If there is no such node, return None.
Example 1
root=tree_node([20, 10, 30, 5, 15, 25]), key=10 → [10, 5, 15]

Node 10 is found and returned together with its children 5 and 15.

Example 2
root=tree_node([20, 10, 30, 5, 15, 25]), key=17 → None

17 lies between 10 and 20, so it would be the right child of 15, and that spot is empty. The answer is None.

Example 3
root=tree_node([8, None, 12, 9]), key=12 → [12, 9]
Constraints
  • 1 ≤ number of nodes ≤ 5000
  • 1 ≤ node value ≤ 10⁷
  • root is a valid search tree with distinct values
  • 1 ≤ key ≤ 10⁷
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBalanced Tree from a Sorted List EasyNearest Value in a Search Tree EasyMost Frequent Values in a Search Tree EasyPair Sum in a Search Tree EasyClosest Pair in a Search Tree Easy
loading Python…
Input
root=tree_node([20, 10, 30, 5, 15, 25]), key=10
Expected
[10, 5, 15]

Run checks the first 3 tests in your browser. Submit checks all 38 tests on the server, hidden ones included.