```
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root)
;
else if (key < root->val)
root->left = deleteNode(root->left, key);
else if (key > root->val)
root->right = deleteNode(root->right, key);
else {
if (!root->right) {
TreeNode *ans = root->left;
delete root;
return ans;
}
TreeNode *cur = root->right, *parent = NULL;
while (cur->left) {
parent = cur;
cur = cur->left;
}
root->val = cur->val;
if (parent)
parent->left = deleteNode(parent->left, root->val);
else
root->right = deleteNode(root->right, root->val);
}
return root;
}
};
```