Trim a Binary Search Tree

Given the `root` of a binary search tree and the lowest and highest boundaries as `low` and `high`, trim the tree so that all its elements lie in `[low, high]`. Trimming the tree should **not** change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a **unique answer**. Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

30:00

Trim a Binary Search Tree
medium
Free written solution
Topics
Companies

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lie in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

Example 1:
Input: {"root":[3,0,4,null,2,null,null,1],"low":1,"high":3}
Output: [3,2,null,1]
Constraints:
  • The number of nodes in the tree is in the range [1,104][1, 10^4].

  • 0≤Node.val≤1040 \leq \text{Node.val} \leq 10^4

  • The value of each node in the tree is unique.

  • root is guaranteed to be a valid binary search tree.

  • 0≤low≤high≤1040 \leq \text{low} \leq \text{high} \leq 10^4

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

Run code to see results.

Input
arr ={"root":[3,0,4,null,2,null,null,1],"low":1,"high":3}

The tree is drawn in value order, so the window [1, 3] is a vertical band. Every node outside the band must go, but nodes inside keep their ancestor/descendant order.

bst in value order, window [1, 3]

kept 0 · cut 0 · of 5

low 1high 330421

window band

cut now

kept

current / promoted

call stack

(empty)

Variables
VariableValue
low1
high3
nodes5
DepthFunction Call
Stack empty
0/16