Thursday, January 10, 2019

776. Split BST



Version #1 recursive
Time O(nlogn) if balanced - O(n) in worst case

I feel this one is super super hard to understand...

class Solution {
    public TreeNode[] splitBST(TreeNode root, int V) {
// res[0] resp[1] -> one is the root itself, the other one is the new root elected from splitting
if (root == null) {
return new TreeNode[]{null, null};
}
TreeNode[] res = null;
if (root.val <= V) { // root become res[0], res[1] would be elected from its right subtree
res = splitBST(root.right, V);
// root is res[0] -> res[0] will become the new right child of root
root.right = res[0];
res[0] = root;
} else {
res = splitBST(root.left, V);
root.left = res[1];
res[1] = root;
}
return res;
}
}

No comments:

Post a Comment