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 than 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 a list of the two roots of the two subtrees, in that order.
Function Signature
def split_bst(root: Optional[TreeNode], target: int) -> List[Optional[TreeNode]]:
Rules
-
TreeNode
has the fields
val
,
left
and
right
. In the examples a tree is written as its level-order list, with
None
for a missing child and trailing
None
values dropped. An empty tree is written as
None
.
-
Return
[small_root, large_root]
.
small_root
holds every node with value at most
target
, and
large_root
holds every node with value greater than
target
. Either one can be
None
.
-
Reuse the original nodes. When a node's original parent ends up in the other tree, the node hangs under its nearest original ancestor that is in the same tree as the node, on the side that BST order requires. A node with no such ancestor is the root of its tree. This makes the expected output unique.
Constraints
-
The number of nodes in the tree is in the range 1 to 50.
-
0 <= Node.val, target <= 1000
Examples
Input: root = [4,2,6,1,3,5,7], target = 2
Output: [[2,1], [4,3,6,None,None,5,7]]
Nodes 1 and 2 are at most 2, so node 2 keeps its left child 1 and loses its right child 3. The parent of node 3 moved to the other tree, so 3 hangs under its nearest ancestor on the greater side, node 4, as its left child.
Input: root = [4,2,6,1,3,5,7], target = 5
Output: [[4,2,5,1,3], [6,None,7]]
Nodes 1 to 5 form the first tree. The parent of node 5 is node 6, which is greater than 5, so node 5 attaches to its nearest ancestor on the smaller side, node 4, as its right child. Node 6 keeps its right child 7 and becomes the root of the second tree.
Input: root = [1], target = 1
Output: [[1], None]
The only node has value 1, which is at most the target, so it goes to the first tree and the second tree is empty.