Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted. \
Basically, the deletion can be divided into two stages:
- Search for a node to remove. O(log n)
- If the node is found, delete the node. O(1)
Delete the node:
- Balance the tree by moving the right child up
- assign left child to right child's leftmost (left child must be smaller than right's leftmost)
COULD BE IMPROVED
Time: O(log n)
Space: O(h)
Recursive
public TreeNode deleteNode(TreeNode root, int key) {
TreeNode dummy = new TreeNode();
dummy.right = root;
TreeNode parent = dummy;
parent = findDeletedParent(root, parent, key);
if (parent != null) {
boolean isLeftChild = parent.left != null && parent.left.val == key;
TreeNode deleted = isLeftChild ? parent.left:parent.right;
TreeNode left = deleted.left;
TreeNode right = deleted.right;
// balance the tree
// move the right subtree up
if (isLeftChild)
parent.left = right;
else
parent.right = right;
// put left subtree on the right subtree's leftmost
if (right != null) {
while (right.left != null)
right = right.left;
right.left = left;
}
// if the right subtree is empty, move the left subtree up
else {
if (isLeftChild)
parent.left = left;
else
parent.right = left;
}
}
return dummy.right;
}
private TreeNode findDeletedParent(TreeNode root, TreeNode parent, int key) {
if (root == null) return null;
if (root.val == key) return parent;
TreeNode left = null, right = null;
if (root.val < key) right = findDeletedParent(root.right, root, key);
if (root.val > key) left = findDeletedParent(root.left, root, key);
return left == null ? right:left;
}