删除二叉搜索树中的节点
题目描述
给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
一般来说,删除节点可分为两个步骤:
首先找到需要删除的节点;
如果找到了,删除它。
解题思路
解题过程分三步:
- 找到需要删除的节点;
- 删除;
- 调整删除后的树。
首先根据二叉搜索树的特性去寻找被删除节点;
当找到节点后有四种情况:
- 没有左右子树——直接删除即可;
- 只有左子树——返回左子树,删除节点;
- 只有右子树——返回右子树,删除节点;
- 左右子树都有——把左子树放在右子树的最左节点下作为左子树(其实反过来,把右子树放在左子树的最右节点的右子树也可以)。
题解
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr){
return root;
}
// 寻找到了目标节点
if(root->val == key){
if(!root->left && !root->right){
delete root;
return nullptr;
cout << "1";
}
else if(!root->left && root->right){
TreeNode* temp = root->right;
delete root;
return temp;
cout << "2";
}
else if(root->left && !root->right){
TreeNode* temp = root->left;
delete root;
return temp;
cout << "3";
}
else {
TreeNode* templ = root->left;
TreeNode* temp2 = root->right;
TreeNode* cur = root->right;
while(cur->left != nullptr){
cur = cur->left;
}
cur->left = templ;
delete root;
return temp2;
cout << "4";
}
}
else if(root->val > key){
root->left = deleteNode(root->left, key);
}
else if(root->val < key){
root->right = deleteNode(root->right, key);
}
return root;
}
};
634

被折叠的 条评论
为什么被折叠?



