Trim a Binary Search Tree
Problem statement
Given the root of a binary search tree and an inclusive range [low, high], remove every node whose value is outside the range.
Keep the relative structure of retained nodes unchanged. Return the trimmed root; a retained descendant may become the new root.
Function
trimBST(root: TreeNode, low: int, high: int) → TreeNodeExamples
Example 1
root = [1,0,2]low = 1high = 2return = [1,null,2]Node 0 is below the range and is removed.
Example 2
root = [3,0,4,null,2,null,null,1]low = 1high = 3return = [3,2,null,1]The branch rooted at 4 is too large. Valid descendants from the left branch remain in BST order.
Example 3
root = [0,null,1]low = 1high = 2return = [1]The original root is too small, so its retained right child becomes the new root.
Constraints
- The tree contains between
0and100000nodes. -1000000000 <= Node.val, low, high <= 1000000000.low <= high.- All node values are distinct, and the input is a valid binary search tree.