# 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 classSolution: defdeleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: current, parent = root, None while current and current.val != key: # 找到要删除的节点,以及它的父节点 parent = current current = current.left if current.val > key else current.right if current isNone: # 不存在该节点 return root elif current.left isnotNoneand current.right isnotNone: # 如果被删除节点拥有左右子节点,找到左子树中的最大节点current successor, successor_parent = current.left, current while successor.right: # 遍历到最右后,就找到了最大节点 successor_parent = successor successor = successor.right if successor_parent.val == current.val: # 如果这个最大元素节点就是被删除节点的左子节点,那么需要把该左子节点的左子节点挂在它父节点的左子节点上 successor_parent.left = successor.left else: # 如果这个最大元素节点不是被删除节点的左子节点,那么要把这个最大元素节点的父节点的右子节点指向该最大元素节点的左子节点 successor_parent.right = successor.left successor.left = current.left successor.right = current.right current = successor else: if current.left isNone: current = current.right elif current.right isNone: current = current.left else: current = None if parent isNone: return current elif parent.left and parent.left.val == key: parent.left = current else: parent.right = current return root
classSolution: defdeleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: current, parent = root, None while current and current.val != key: parent = current current = current.left if current.val > key else current.right if current isNone: return root if current.left isNoneand current.right isNone: current = None elif current.left isNone: current = current.right elif current.right isNone: current = current.left else: successor, successor_parent = current.left, current while successor.right: successor_parent = successor successor = successor.right if successor_parent.val == current.val: successor_parent.left = successor.left else: successor_parent.right = successor.left successor.left = current.left successor.right = current.right current = successor if parent isNone: return current elif parent.left and parent.left.val == key: parent.left = current else: parent.right = current return root