# 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 successor(self, node):
while node.left:
node = node.left
return node.val
def precessor(self, node):
while node.right:
node = node.right
return node.val
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root:
return None
if root.val < key:
root.right = self.deleteNode(root.right, key)
elif root.val > key:
root.left = self.deleteNode(root.left, key)
else:
if not root.right and not root.left:
root = None
elif root.right:
root.val = self.successor(root.right)
root.right = self.deleteNode(root.right, root.val)
else:
root.val = self.precessor(root.left)
root.left = self.deleteNode(root.left, root.val)
return root
删除二叉搜索树中的节点-二叉树450-python
最新推荐文章于 2022-06-22 16:52:03 发布