删除二叉搜索树中的节点
[题目](450. 删除二叉搜索树中的节点)
重点
五种情况: 没找到要删除的节点 左为空,右为空 左不空,右为空 左为空,右不空 左不空,右不空
代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
// 没找到要删除的节点
if (!root) {
return root;
}
if (root->val == key) {
// 左右孩子都为空(叶子节点),直接删除节点,返回NULL为根节点
if (!root->left && !root->right) {
delete root;
return nullptr;
}
// 左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点
else if (!root->left) {
auto retNode = root->right;
delete root;
return reNode;
}
// 右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
else if (!root->right) {
auto retNode = root->left;
delete root;
return reNode;
}
// 左右孩子都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子位置
else {
// 找右子树最左面的节点
auto cur = root->right;
while (cur->left) {
cur = cur->left;
}
// 把要删除的节点(root)左子树放到cur的左孩子的位置
cur->left = root->left;
// root节点保存一下,下面需要删除
auto tmp = root;
// 返回右孩子,操作和左孩子为空,右孩子不为空的情况
root = root->right;
delete tmp;
return root;
}
}
if (root->val > key) {
root->left = deleteNode(root->left, key);
}
if (root->val < key) {
root->right = deleteNode(root->right, key);
}
return root;
}
};