Leetcode 669. Trim a Binary Search Tree
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 lie in [low, high]
. Trimming the tree should not change the relative structure of the remaining nodes. It should be a new tree that satisfies the given bounds.
null
if no node in the tree falls within the given bounds.low
and high
follow any particular order?
low
≤ high
.null
, return null
.low
, then the entire left subtree of this node will also be out of range (because in a BST, all values in the left subtree are less than the node’s value). We, therefore, trim the left subtree and return the result of trimming the right subtree.high
, then the entire right subtree of this node will also be out of range. We, therefore, trim the right subtree and return the result of trimming the left subtree.[low, high]
, we recursively trim both the left and right subtrees of the node.Here is the Java implementation based on the above strategy:
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val < low) {
return trimBST(root.right, low, high);
}
if (root.val > high) {
return trimBST(root.left, low, high);
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
O(n)
, where n
is the number of nodes in the tree. In the worst case, we need to visit every node to either discard it or include it in the trimmed tree.O(h)
, where h
is the height of the tree. In the worst case (for a skewed tree), it will require space proportional to the height of the tree due to the recursion stack.This solution ensures that the resulting tree contains only nodes within the [low, high]
range, preserving the structure of the BST.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?