1662. Divide the Search Tree

A library shelf index is a binary search tree of distinct catalogue numbers. Given a number target (which need not be in the tree), split the index into two search trees: one holding every number less than or equal to target and one holding every number greater than it. Either tree may be empty.

The result is defined uniquely by recursion on the root: if root.val <= target, the root stays in the smaller tree with its left subtree untouched, and its right child becomes the smaller tree obtained by splitting the old right subtree, while the larger tree of that split is returned as the second tree. Symmetrically when root.val > target. Reuse the existing nodes, touching only the search path for target. Return [smallerRoot, largerRoot]. Time O(h), space O(1) extra.

Example 1

Input:
root = [50,30,70,20,40,60,80], target = 45
Output:
[[30,20,40],[50,null,70,60,80]]
Explanation:

Since 50 exceeds 45 it goes to the larger tree; its left subtree is split into 30 with children 20 and 40, all at most 45, so they form the smaller tree.

Example 2

Input:
root = [50,30,70,20,40,60,80], target = 70
Output:
[[50,30,70,20,40,60],[80]]
Explanation:

Keys up to 70 stay in the smaller tree, so 70 loses its right child 80, which alone forms the larger tree.

Constraints

1 ≤ nodes ≤ 500; keys are distinct; -106 ≤ keys, target ≤ 106; the input is a valid binary search tree

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(h)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…