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 lies 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.
Input: root = [1,0,2], low = 1, high = 2
Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Constraints:
root is guaranteed to be a valid binary search tree.The idea is to recursively traverse the tree and rebuild it by considering the constraints of a binary search tree (BST). For each node:
low, then discard the left subtree (because all values in the left subtree are also less than low) and trim the right subtree.high, discard the right subtree and trim the left subtree.[low, high], then keep the node and recursively trim both its left and right subtrees.The base case for the recursion is when a null node is encountered.
This approach uses an iterative Depth-First Search (DFS) strategy with a stack to avoid the recursion overhead. The idea is the same as the recursive approach, but maintains a stack to process the nodes iteratively.