1. Description
Given a BST and a key, delete the node with the given key in the BST.
2. Solution
If the root's value is equal to k, there are four cases to analyse.
Otherwise, try to delete the node with k from the left-child and right-child, update the root's two child, and return the root.
3. Code
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root) return NULL;
if(root->val ==key){
TreeNode* l = root->left;
TreeNode* r = root->right;
if(!l&&!r) return NULL;
else if(!r) return l;
else if(!l) return r;
else{
root = r;
while(r->left){
r=r->left;
}
r->left = l;
return root;
}
}
else{
TreeNode* l = deleteNode(root->left,key);
TreeNode* r = deleteNode(root->right,key);
root->left = l;
root->right = r;
return root;
}
}