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.
Note: Time complexity should be O(height of tree).
Example:
root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \ 2 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7
查找并删除BST中某个结点。
这道题,在我写了96行代码还在wa后,对你没看错,96行!我果断放弃了这个代码,围观评论区大神orzzzzzzz
然后发现自己蠢的没救了。。。为啥非要执着于把那个结点删除然后调个结点过来呢,咱就不能直接改变结点值么然后再去删除想要调的那个结点么!!!震惊哭QAQ
递归简直是脑残人的救星,在不会做的情况下,我还是不要纠结非得写非递归吧,找块豆腐撞死算了。
一路搜索下去,沿途改变各个结点的左右状态,一直都搜索到key结点,找到key的右子树中值最小的结点,赋值给key,并删除这个结点。时间复杂度O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) return root;
if (key < root->val)
root->left = deleteNode(root->left, key);
else if (key > root->val)
root->right = deleteNode(root->right, key);
else {
if (!root->left)
return root->right;
if (!root->right)
return root->left;
TreeNode* cur = finMin(root->right);
root->val = cur->val;
root->right = deleteNode(root->right, cur->val);
}
return root;
}
TreeNode* finMin(TreeNode* root) {
while (root->left)
root = root->left;
return root;
}
};