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.
Input & Output
Constraints
- The number of nodes in the tree is in the range [0, 100]
- 0 ≤ Node.val ≤ 100
- 0 ≤ target ≤ 100
- The tree is a valid BST (left subtree values < root < right subtree values)