class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root==nullptr) return nullptr;
if(root->val>key){
root->left = deleteNode(root->left,key);
}else if(root->val<key){
root->right = deleteNode(root->right,key);
}else{
if(!root->left&&!root->right){
return nullptr;
}
if(root->left==nullptr){
return root->right;
}
TreeNode* right = root->right;
TreeNode* node = root->left;
while(node->right){
node=node->right;
}
node->right = right;
root = root->left;
}
return root;
}
};
刷题记录第七十九天-删除二叉搜索树中的节点
![](https://img-home.csdnimg.cn/images/20240711042549.png)