版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84074684
题目:
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中的一个结点,使得删除后树还是一个BST
有多种删除方法
递归,如果val小于当前结点的val,在其左子树中找,反之亦然~
1.结点没有左子树:返回其右子树
2.结点没有右子树:返回其左子树
3.结点既有左子树,又有右子树:
1)在右子树中找一个值最小的结点,替换被删除的结点,并删除找到的最小结点(左孩子的左孩子的左孩子……)
root.val = minNode.val;
root.right = deleteNode(root.right, root.val);
或者
2)在左子树中找到一个值最大的结点,替换被删除的结点,并删除找到的最大结点(右孩子的右孩子的右孩子……)
python代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
def findMax(root):
if not root:
return None
while root.right:
root=root.right
return root
def findMin(root):
if not root:
return None
while root.left:
root=root.left
return root
if not root:
return None
if root.val>key:
root.left=self.deleteNode(root.left,key)
elif root.val<key:
root.right=self.deleteNode(root.right,key)
else:
if not root.left:
return root.right
elif not root.right:
return root.left
else:
# minNode=findMin(root.right)
# root.val=minNode.val
# root.right=self.deleteNode(root.right,root.val)
maxNode=findMax(root.left)
root.val=maxNode.val
root.left=self.deleteNode(root.left,root.val)
return root
c++代码:
/**
* 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 NULL;
if(key>root->val)
root->right=deleteNode(root->right,key);
else if(key<root->val)
root->left=deleteNode(root->left,key);
else
{
if(!root->left)
return root->right;
else if(!root->right)
return root->left;
else
{
TreeNode* maxNode=findMax(root->left);
root->val=maxNode->val;
root->left=deleteNode(root->left,maxNode->val);
}
}
return root;
}
TreeNode* findMax(TreeNode* root)
{
if (!root)
return NULL;
while(root->right)
root=root->right;
return root;
}
};
总结: