Approach
I was originally thinking that we need to find the delete node, and find its parent, and then do some tree operations to reconnect the tree nodes.
However, I saw that ususally people tries to copy the successor or predecessors value instead of removing it. In this case the implementation could be more easy.
We recursively calling the “deleteNode”. When no child, return nullptr. When one child, remove current node and return that child. For two child, we replace the current node with its successor or predecessor.
Code
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr) return root;
if(key > root->val) {
root->right = deleteNode(root->right, key);
} else if(key < root->val) {
root->left = deleteNode(root->left, key);
} else {
if(root->left == nullptr && root->right == nullptr) return nullptr;
if(root->left == nullptr || root->right == nullptr) {
return root->left == nullptr ? root->right : root->left;
}
TreeNode * successor = root->right;
while(successor->left != nullptr) successor = successor->left;
root->val = successor->val; // copy value and reuse pointer
root->right = deleteNode(root->right, root->val);
}
return root;
}
};