oneby7

Binary Search Trees Using the ordering

396. Trim a Binary Search Tree

Medium

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

root
712182329344052586581
output
12182329344052

Input: root = [40, 18, 65, 7, 29, 52, 81, null, 12, 23, 34, null, 58] low = 10 high = 55

Output: [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

1234569
root
345
output

Input: root = [6, 2, 9, 1, 4, null, null, null, null, 3, 5] low = 3 high = 5

Output: [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

−10⁹010⁹

Input: root = [0, -1000000000, 1000000000] low = 1 high = 999999999

Output: []

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.

root = [20, 10, 30, 5, 15, 25, 35] low = 10 high = 25

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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.