LeetCode 450.删除二叉树中的节点
题目链接:https://leetcode.cn/problems/delete-node-in-a-bst/
题目
解答
递归法
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == NULL) return NULL;
if(root->val == key){
if(root->left == NULL) return root->right;
else if(root->right == NULL) return root->left;
else {
TreeNode* cur = root->right;
while(cur->left != NULL) {
cur = cur->left;
}
cur->left = root->left;
TreeNode* 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;
}
};