Binary Search Trees BST basics
382. Search in a Binary Search Tree
You are given root, the root node of a binary search tree, and an integer val. Find the node that holds
val and return it. The node brings everything below it, so the answer is the subtree rooted at that node.
If no node holds val, return null.
In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. The values in the tree are distinct.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out. The output shows the subtree you return the same way,
and null as [].
Example 1
Input: root = [41, 17, 73, 8, 29, 60, 95, null, null, 23, 35]
val = 29
[29,23,35]Explanation: The node 29 is the right child of 17. Its subtree holds 29 and its two children, 23 and 35.
Example 2
Input: root = [8, 3, 10, 1, 6], val = 7
[]Explanation: No node holds 7, so the answer is null.
Example 3
Input: root = [0, -1000000000, 1000000000], val = 0
[0,-1000000000,1000000000]Explanation: The root holds 0, so the answer is the whole tree.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
- The tree is a binary search tree, and its values are distinct.
-109 ≤ val ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.