The Split BST coding problem involves taking a Binary Search Tree (BST) and a target value. You need to split the tree into two separate subtrees: one containing all nodes with values less than or equal to the target, and the other containing all nodes with values greater than the target. The original structure of the tree should be maintained as much as possible, and both resulting subtrees must still satisfy the BST property.
This problem is common in Amazon and Coupang interviews because it tests a candidate's mastery of recursion and their understanding of tree properties. Unlike simple traversals, this problem requires you to modify tree pointers and return multiple values (the roots of the two new subtrees). It's an excellent test of your mental model of how recursive calls return and how they can be used to build or modify complex data structures.
The Algorithmic pattern used here is Recursion on a Tree. Since it's a BST, we can use the property that left is smaller and right is larger to decide which way to go. If the current node's value is target, then the current node and its entire left subtree belong to the "smaller" group. However, some nodes in its right subtree might also be target. We recursively split the right child. The part of the right child that is target becomes the new right child of our current node, and the part that is target is returned as the root of the "larger" tree.
Imagine a BST with root 4, left child 2, and right child 6. Target is 3.
To excel at Recursion, Binary Search Tree, Binary Tree, Tree interview pattern problems, practice drawing out the tree on a whiteboard. Trace the recursive calls and see how the pointers change at each step. Understanding how the "return" value of a function can be used to update the "current" node's children is key to solving tree mutation problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Insert into a Binary Search Tree | Medium | Solve | |
| Delete Node in a BST | Medium | Solve | |
| Inorder Successor in BST II | Medium | Solve | |
| Search in a Binary Search Tree | Easy | Solve | |
| Convert BST to Greater Tree | Medium | Solve |