The "Trim a Binary Search Tree coding problem" involves modifying an existing Binary Search Tree (BST) so that all its elements fall within a given range [low, high]. Trimming means removing nodes that are outside the range while maintaining the BST properties. If a node's value is less than low, its entire left subtree must also be removed. If it's greater than high, its entire right subtree must be removed.
This "Trim a Binary Search Tree interview question" is a favorite at companies like Microsoft and Bloomberg because it tests your understanding of the core property of a BST: for any node, all values in the left subtree are smaller, and all values in the right subtree are larger. It evaluates your ability to use recursion to restructure a tree efficiently without creating new nodes unnecessarily.
The "Binary Search Tree, Depth-First Search, Binary Tree, Tree interview pattern" is used here recursively.
null, return null.root.val < low, the root and its left subtree are out of range. We return the result of trimming the right subtree.root.val > high, the root and its right subtree are out of range. We return the result of trimming the left subtree.BST: 3 (root), 0 (left), 4 (right), 2 (right child of 0). Range: [1, 3].
One major error in the "Trim a Binary Search Tree coding problem" is not correctly re-linking the nodes. Candidates often forget to update root.left and root.right with the results of the recursive calls. Another mistake is trying to handle the cases iteratively, which is much more complex for tree restructuring than a simple recursive approach.
To excel in the "Binary Search Tree, Depth-First Search, Binary Tree, Tree interview pattern," focus on the "post-order" or "pre-order" nature of the transformation. In this case, we determine the fate of the current node before (or while) processing its children. Practice tree problems that require returning a modified TreeNode to get comfortable with this pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Binary Search Tree to Greater Sum Tree | Medium | Solve | |
| Convert BST to Greater Tree | Medium | Solve | |
| Recover Binary Search Tree | Medium | Solve | |
| Kth Smallest Element in a BST | Medium | Solve | |
| Lowest Common Ancestor of a Binary Search Tree | Medium | Solve |