[Oracle] LeetCode 450 Delete Node in a BST
Given a root
node reference of a BST and a key, delete the node with the given key in the BST. Return the root
node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
- Search for a node to remove.
- If the node is found, delete the node.
Solution
运用递归的方法来进行删除。首先根据 \(key\) 与当前节点的值,来判断是在左子树还是右子树。
当找到节点时,我们在右子树上不断找左子树的最后一个点,将这个点作为节点来补到原来的位置(因为这样才能满足 \(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 root;
if(root->val > key){
root->left = deleteNode(root->left, key);
}
else if(root->val < key){
root->right = deleteNode(root->right, key);
}
else{
if(!root->right)return root->left;
else if(!root->left)return root->right;
else{
TreeNode* tmp = root->right;
while(tmp->left)tmp=tmp->left;
root->val = tmp->val;
root->right = deleteNode(root->right,tmp->val);
}
}
return root;
}
};