Sponsored
Sponsored
We can utilize the properties of a BST to perform a recursive traversal. The strategy here involves:
low
, we need to trim the left subtree and consider the right subtree.high
, we trim the right subtree and consider the left subtree.low
, high
], we recursively trim both subtrees.Time Complexity: O(n), where n is the number of nodes in the tree, since each node is processed once.
Space Complexity: O(h), where h is the height of the tree, representing the recursion stack.
1function TreeNode(val) {
2 this.val = val;
3 this.left = this.right = null;
4}
5
6var trimBST = function(root, low, high) {
7 if (!root) return null;
8 if (root.val < low) return trimBST(root.right, low, high);
9 if (root.val > high) return trimBST(root.left, low, high);
10 root.left = trimBST(root.left, low, high);
11 root.right = trimBST(root.right, low, high);
12 return root;
13};
The JavaScript solution adopts a similar recursive pattern, calling the function for left or right subtrees based on the root value.
This iterative approach uses a stack to traverse the tree. The main idea is to mimic the recursive depth-first search using an explicit stack.
Time Complexity: O(n), as each node is processed once.
Space Complexity: O(h), where h is the height of the tree, due to the stack usage.
1class TreeNode:
2
The Python solution employs a stack for an iterative node traversal. Adjustments are made according to the node values relative to low
and high
. Nodes are appended to a stack for traversal if they are valid.