题目链接:https://leetcode-cn.com/problems/delete-node-in-a-bst/
题目如下:
/**
* 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 nullptr;
if(root->val==key){
if(!root->left) return root->right;//其左孩子为空,右孩子不为空
else if(!root->right) return root->left;//其右孩子为空,左孩子不为空
else {//其左右孩子均不为空
//找到当前节点右子树的最左叶子节点
TreeNode* cur=root->right;
while(cur->left){
cur=cur->left;
}
cur->left=root->left;//在这个最左叶子节点上存放root->left
TreeNode* tmp=root;//存放目前将要删除的节点
root=root->right;
delete tmp;
return root;
}
}
if(root->val>key) root->left=deleteNode(root->left,key);
else if(root->val<key) root->right=deleteNode(root->right,key);
return root;//左右孩子都为空
}
};