题目:
代码(首刷看解析):
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root==nullptr){
return nullptr;
}
if(root->val > key ){
root->left = deleteNode(root->left,key);
return root;
}
if(root->val < key ){
root->right = deleteNode(root->right,key);
return root;
}
if(root->val == key){
if(root->left==nullptr && root->right == nullptr){
return nullptr;
}
if(root->left==nullptr){
return root->right;
}
if(root->right==nullptr){
return root->left;
}
if(root->right&&root->left){
TreeNode* successor = root->right;
while(successor->left){
successor=successor->left;
}
root->right=deleteNode(root->right,successor->val);
successor->right=root->right;
successor->left=root->left;
return successor;
}
}
return root;
}
};
代码(二刷看解析 2024年1月31日)
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) return nullptr;
if (root->val == key) {
if (!root->left && !root->right){
delete root;
return nullptr;
}
else if (!root->left) {
auto ret = root->right;
delete root;
return ret;
}
else if (!root->right) {
auto ret = root->left;
delete root;
return ret;
}
else{
TreeNode* cur = root->right;
while (cur->left) {
cur = cur->left;
}
cur->left = root->left;
auto ret = root;
root = root->right;
delete ret;
return root;
}
}
if(key < root->val) root->left = deleteNode(root->left, key);
if(key > root->val) root->right = deleteNode(root->right,key);
return root;
}
};