#669

Trim a Binary Search Tree

specialist · 610 · lc medium +29 · verified · 66.6% accepted · 6,088 likes · top 72%

Description

You are given the root of a binary search tree along with boundary values low and high. Remove all nodes whose values fall outside the range [low, high], while preserving the relative structure among the remaining nodes (descendants must remain descendants). A unique answer is guaranteed.

Return the root of the resulting trimmed tree, which may differ from the original root.

Example 1:

Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]

Example 2:

Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]

Code

1
2
3
4
5
6
7
8
9