658. Split BST
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]]
Explanation:
- The subtree containing nodes ≤ 2 should be extracted.
- The left subtree rooted at 2 (with children 1) qualifies.
- The node 3 is greater than 2, so it must move to the right subtree.
- The remaining tree should contain nodes > 2, and 3 should be placed correctly in it.
Example 2:
Input: root = [1,2], target = 1
Output: [[1],[2]]
Explanation:
- The subtree containing nodes ≤ 1 should be extracted.
- Since 1 itself is ≤ target, it belongs to the left subtree.
Now Your Turn!
Pick the correct output for the given inputInput: root = [4,null,66,13,null,null,24,null,null] , target = 4
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- The number of nodes in the tree is in the range [1, 50].
- 0 <= Node.val, target <= 1000