Imagine you have a Binary Search Tree (BST) and need to split it into two separate trees based on a target value. This is like organizing a library where you want to separate books into two sections: one for books with ID numbers ≤ target, and another for books with ID numbers > target.
Given the root of a BST and an integer target, you need to split the tree into two subtrees:
Left subtree: Contains all nodes with values ≤ target
Right subtree: Contains all nodes with values > target
The challenge is to preserve the original tree structure as much as possible. If a parent-child relationship existed in the original tree and both nodes end up in the same subtree, that relationship should be maintained.
Important: The target value might not exist in the tree, but you still need to perform the split based on that value.
Return an array [leftRoot, rightRoot] where leftRoot is the root of the subtree with values ≤ target, and rightRoot is the root of the subtree with values > target.
The optimal recursive approach leverages BST properties to split the tree in O(n) time while preserving the original structure. At each node, we decide which result tree it belongs to based on the target comparison, then recursively split the appropriate subtree and connect the results properly.
Common Approaches
✓
Brute Force (Inorder + Rebuild)
⏱️ Time: O(n²)
Space: O(n)
First perform an inorder traversal to collect all values, separate them based on the target, then construct two new BSTs from the separated values. This approach completely rebuilds the trees.
Optimal Recursive Split
⏱️ Time: O(n)
Space: O(h)
Use the BST property to recursively determine where to split the tree. At each node, decide whether it belongs in the left or right result tree, and recursively split its subtrees accordingly. This preserves the original structure.
Brute Force (Inorder + Rebuild) — Algorithm Steps
Perform inorder traversal to collect all node values