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.
Example 1:
Input: root = [5,3,6,2,4,null,7], key = 3 Output: [5,4,6,2,null,null,7] Explanation: 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 above BST. Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.
Example 2:
Input: root = [5,3,6,2,4,null,7], key = 0 Output: [5,3,6,2,4,null,7] Explanation: The tree does not contain a node with value = 0.
Example 3:
Input: root = [], key = 0 Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 104]
. -105 <= Node.val <= 105
- Each node has a unique value.
root
is a valid binary search tree.-105 <= key <= 105
要删除一个节点,最直观的就是找到这个节点然后删除它,但是要保证删除后的树还得是一棵二叉查找树(BST)。
传统的数据结构与算法书是按以下4种情况进行处理:
1) 叶节点,即没有左子树和右子树
2)只有左子树没有右子树
3)只有右子树没有左子树
4)既有左子树又有右子树
其实这道题我们可以简化为两种情况:右子树为空和不为空。
1)如果要删除的节点的右子树为空,只要把该节点的父节点指向该节点的左子树(左子树空与不空可以一样处理)
2)如果要删除的节点的右子树不为空,则找到右子树的最左侧节点即后继节点(Successor), 然后把要删除节点的左子树(不管为空或不为空)作为后继节点的左子树,最后把要删除节点的父节点指向该节点的右子树即可。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
def helper(parent, node) :
if not node :
return
if key < node.val :
helper(node, node.left)
return
if key > node.val :
helper(node, node.right)
return
if key == node.val :
if not node.right : #右子树为空
cur = node.left
else : #右子树不为空
cur = node.right
successor = cur
#查找最左测节点 Successor
while successor.left :
successor = successor.left
#删除节点的左子树赋给后继节点
successor.left = node.left
if parent.left == node :
parent.left = cur
else:
parent.right = cur
#新建一个节点作为根节点的父节点,这样就不要管删除的是否为根节点
parent = TreeNode(-1, root)
helper(parent, root)
return parent.left
注:这种解法的缺点是会破坏树的平衡性