Split BST

medium trees bst recursion

Problem

Given a BST and a value V, split it into two BSTs: one with all keys <= V and one with all keys > V, preserving the original tree structure as much as possible.

Inputroot=[4,2,6,1,3,5,7], V=2
Output[[2,1],[4,3,6,null,null,5,7]]
Two BSTs partitioned by V=2.

def splitBST(root, V):
    if not root: return [None, None]
    if root.val <= V:
        left, right = splitBST(root.right, V)
        root.right = left
        return [root, right]
    else:
        left, right = splitBST(root.left, V)
        root.left = right
        return [left, root]
function splitBST(root, V) {
  if (!root) return [null, null];
  if (root.val <= V) {
    const [l, r] = splitBST(root.right, V);
    root.right = l;
    return [root, r];
  } else {
    const [l, r] = splitBST(root.left, V);
    root.left = r;
    return [l, root];
  }
}
TreeNode[] splitBST(TreeNode root, int V) {
    if (root == null) return new TreeNode[]{null, null};
    if (root.val <= V) {
        TreeNode[] p = splitBST(root.right, V);
        root.right = p[0];
        return new TreeNode[]{root, p[1]};
    } else {
        TreeNode[] p = splitBST(root.left, V);
        root.left = p[1];
        return new TreeNode[]{p[0], root};
    }
}
vector<TreeNode*> splitBST(TreeNode* root, int V) {
    if (!root) return {nullptr, nullptr};
    if (root->val <= V) {
        auto p = splitBST(root->right, V);
        root->right = p[0];
        return {root, p[1]};
    } else {
        auto p = splitBST(root->left, V);
        root->left = p[1];
        return {p[0], root};
    }
}
Time: O(h) Space: O(h)