Trim a Binary Search Tree
Advertisement
Problem
Given a BST and range [low, high], trim the tree so all node values are within the range. Return the new root.
Key insight: If node.val < low, the answer is in right subtree. If node.val > high, answer is in left subtree.
Solutions
// C
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (!root) 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;
}
// C++
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (!root) return nullptr;
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;
}
// Java
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;
}
// JavaScript
function trimBST(root, low, high) {
if (!root) 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;
}
# Python
def trimBST(root, low, high):
if not root:
return None
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
Complexity
- Time: O(n)
- Space: O(h)
Key Insight
BST property lets us skip entire subtrees — if node < low, whole left subtree is also < low.
Advertisement
← Previous
Serialize and Deserialize BST