Trim a Binary Search Tree (LeetCode 669): Solution and Explanation
Remove every node whose value lies outside [low, high] from a BST while keeping the ancestor and descendant order of the nodes that remain.
Intuition
The BST order does most of the work. If a node's value is below low, everything in its left subtree is even smaller, so that node and its entire left side can be thrown away in one step without looking at them.
What can survive below such a node is only its right subtree. Trimming that right subtree gives exactly the tree that should sit where the node used to be, so the node is replaced by the trimmed right side. A node above high is the mirror case: keep only the trimmed left side.
A node inside the window stays where it is. Its two children are trimmed recursively, and whatever comes back is attached as its new left and right child. That is how a deeper subtree gets promoted into the gap left by a removed node.
Approach: Recursive trim with subtree promotion
- If
rootis null, return null. - If
root.val < low, returntrimBST(root.right, low, high): the root and its left subtree are all too small. - If
root.val > high, returntrimBST(root.left, low, high): the root and its right subtree are all too large. - Otherwise set
root.left = trimBST(root.left, low, high)androot.right = trimBST(root.right, low, high). - Return
root.
Step-by-step example
root = [3,0,4,null,2,null,null,1], low = 1, high = 3
- 3 is inside [1, 3], so it stays. Trim its left child 0.
- 0 is below 1. Its left subtree is empty, so the answer for this spot is the trimmed right subtree, rooted at 2.
- 2 is inside the window and stays, and so does its left child 1. The call returns 2, and
3.left = 2promotes it into the gap left by 0. - Back at 3, trim the right child 4. 4 is above 3, its left subtree is empty, so
3.right = null. - The result is
[3,2,null,1].
Code: Python, Java, C++
1class Solution:
2 def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
3 if not root:
4 return None
5 if root.val < low:
6 return self.trimBST(root.right, low, high)
7 if root.val > high:
8 return self.trimBST(root.left, low, high)
9 root.left = self.trimBST(root.left, low, high)
10 root.right = self.trimBST(root.right, low, high)
11 return root1class Solution {
2 public TreeNode trimBST(TreeNode root, int low, int high) {
3 if (root == null) {
4 return null;
5 }
6 if (root.val < low) {
7 return trimBST(root.right, low, high);
8 }
9 if (root.val > high) {
10 return trimBST(root.left, low, high);
11 }
12 root.left = trimBST(root.left, low, high);
13 root.right = trimBST(root.right, low, high);
14 return root;
15 }
16}1class Solution {
2public:
3 TreeNode* trimBST(TreeNode* root, int low, int high) {
4 if (root == nullptr) {
5 return nullptr;
6 }
7 if (root->val < low) {
8 return trimBST(root->right, low, high);
9 }
10 if (root->val > high) {
11 return trimBST(root->left, low, high);
12 }
13 root->left = trimBST(root->left, low, high);
14 root->right = trimBST(root->right, low, high);
15 return root;
16 }
17};Time and space complexity
O(n)
Each node is visited at most once, and nodes inside a discarded subtree are never visited at all.
O(h)
The recursion goes as deep as the tree height h, which is O(log n) for a balanced tree and O(n) for a chain.
Other approaches
Iterative trim (time O(n), space O(1))
First move the root down until it lies inside the window. Then walk down the left spine, replacing any node below low with its right child, and do the mirror walk down the right spine for high. Same answer with O(1) extra space.
Collect and rebuild (time O(n log n), space O(n))
Gather the in-range values with a traversal and insert them into a new BST in preorder. It produces the same structure but allocates new nodes and is easy to get wrong if the insertion order changes.
Delete each out-of-range node (time O(n h), space O(h))
Run the standard BST delete for every value outside the window. Correct, but it does far more work than needed and can reshape the tree differently from the required answer if the delete picks successors.
Common mistakes
- Returning null as soon as a node is out of range. Its other subtree may still hold values inside the window, and they would be lost.
- Recursing into the subtree that is known to be out of range. It is harmless but wasted work; the BST order already rules it out.
- Forgetting that the root itself can be removed. The function must return the new root rather than always returning the original one.
Frequently asked questions
Why is the answer unique?
Removed nodes are replaced only by their surviving descendants, and kept nodes keep every surviving descendant. Under that rule there is exactly one way to rearrange the tree, which is what the recursion builds.
Can the root change?
Yes. If the original root is outside the window, the root of the result is the first in-range node found on the correct side, as in the window [6, 9] on [5,3,8,2,4,7,9], where 8 becomes the root.
Does the trimmed tree stay a valid BST?
Yes. A promoted subtree came from the same side of every ancestor it now hangs under, so all ordering constraints still hold.
What if no value lies in the window?
Every call ends in a removal or an empty subtree, so the function returns null and the answer is the empty tree [].