Trim a Binary Search Tree

Medium

Description

Given a BST and the lowest and highest boundaries as low and high, trim the tree so that all elements are in [low, high]. Return the root of the trimmed tree.

Examples

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

Remove nodes outside [1, 2].

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

Edge case with a single-element array.

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

Node 1 is less than low (2) so it's removed along with its subtree, except node 2 which falls within [2,3]. Node 4 is greater than high (3) so it's removed. The result has node 3 as root with node 2 as its left child.

Constraints

  • 1 ≤ number of nodes ≤ 10⁴
  • 0 ≤ low ≤ high ≤ 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!