Binary Search Trees Using the ordering
396. Trim a Binary Search Tree
You are given root, the root node of a binary search tree, and two integers low and high. Remove every
node whose value is below low or above high, and return the root of the tree that is left. A value equal
to low or high stays. If no value lies in the range, return null.
The nodes that stay must keep their places relative to each other. If a node stays and a node below it also stays, the second node is still below the first one after the trim. Only one tree meets this rule, so the answer is unique. The root may change, since the old root can be one of the nodes that go.
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 tree you return the same way, and
null as [].
Example 1
Input: root = [40, 18, 65, 7, 29, 52, 81, null, 12, 23, 34, null, 58]
low = 10
high = 55
[40,18,52,12,29,null,null,null,null,23,34]Explanation: The node 7 is below 10, so it goes, and its child 12 takes its place under 18. The nodes 65, 81 and 58 are above 55, so they go, and 52 takes the place of 65 under the root.
Example 2
Input: root = [6, 2, 9, 1, 4, null, null, null, null, 3, 5]
low = 3
high = 5
[4,3,5]Explanation: The root 6 and the node 9 are above 5, and 2 and 1 are below 3. They all go. The node 4 becomes the new root, with 3 and 5 still below it.
Example 3
Input: root = [0, -1000000000, 1000000000]
low = 1
high = 999999999
[]Explanation: No value lies between 1 and 999999999, so every node goes and the answer is null.
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 ≤ low ≤ high ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.