Split BST Problem
Description
LeetCode Problem 776.
Given the root of a binary search tree (BST) and an integer target, split the tree into two subtrees where the first subtree has nodes that are all smaller or equal to the target value, while the second subtree has all nodes that are greater than the target value. It is not necessarily the case that the tree contains a node with the value target.
Additionally, most of the structure of the original tree should remain. Formally, for any child c with parent p in the original tree, if they are both in the same subtree after the split, then node c should still have the parent p.
Return an array of the two roots of the two subtrees in order.
Example 1:

Input: root = [4,2,6,1,3,5,7], target = 2
Output: [[2,1],[4,3,6,null,null,5,7]]
Example 2:
Input: root = [1], target = 1
Output: [[1],[]]
Constraints:
- The number of nodes in the tree is in the range
[1, 50]. 0 <= Node.val, target <= 1000
Solution
Approach: Recursion
Compare the root with target. Because the tree is a BST, one side of the root is settled immediately:
- If
root.val <= target, the root belongs to the small tree, and so does its whole left subtree (everything there is even smaller). Only the right subtree can contain nodes of both kinds, so split it recursively intosmallandlarge. The small part of the right subtree stays below the root: setroot.right = small. Return[root, large]. - Otherwise the root and its whole right subtree belong to the large tree. Split the left subtree into
smallandlarge, attachroot.left = large, and return[small, root]. - An empty tree splits into two empty trees.
This keeps as much structure as required: a node only changes its parent when it and its old parent end up in different trees, and each reattached subtree hangs off its closest ancestor on the same side. Both results are still valid BSTs, because each reattached part comes from the same side of the root as the child it replaces.
The target does not have to be in the tree (target = 0 with all values above it gives an empty small tree). The recursion follows one path from the root down, like a BST search.
Complexity: O(h) time and O(h) extra space for the recursion, where h is the height of the tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def splitBST(self, root: Optional[TreeNode], target: int) -> Optional[List[TreeNode]]:
if root is None:
return [None, None]
if root.val <= target:
# root and its whole left subtree are small; only the right subtree has to be split.
small, large = self.splitBST(root.right, target)
root.right = small
return [root, large]
# root and its whole right subtree are large; only the left subtree has to be split.
small, large = self.splitBST(root.left, target)
root.left = large
return [small, root]