📅  最后修改于: 2023-12-03 15:21:39.977000             🧑  作者: Mango
二叉树的删除操作是将指定节点从二叉树中删除的过程。删除节点可能会引起二叉树的结构改变,因此需要谨慎处理。
二叉树的删除操作有以下几种常见方式:
如果需要删除的节点是叶子节点(即没有子节点),则可以直接将该节点从二叉树中删除。
如果需要删除的节点只有一个子节点,可以用该子节点替换该节点,然后将该节点从二叉树中删除。
如果需要删除的节点有两个子节点,可以在其右子树中找到最小节点,将该节点的值复制到要删除的节点中,然后将最小节点从右子树中删除。也可以在其左子树中找到最大节点,用该节点的值替换要删除的节点,然后删除最大节点。
下面是二叉树删除操作的Python代码实现:
class TreeNode:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return str(self.value)
class BinaryTree:
def __init__(self, root=None):
self.root = root
def __repr__(self):
nodes = []
queue = [self.root]
while queue:
node = queue.pop(0)
if node:
nodes.append(node)
queue.append(node.left)
queue.append(node.right)
else:
nodes.append(None)
while nodes[-1] is None:
nodes.pop()
return ' '.join(str(node) if node is not None else '#' for node in nodes)
def delete(self, value):
def find(parent, node, value):
if node is None:
return None
if node.value == value:
return parent, node
if value < node.value:
return find(node, node.left, value)
else:
return find(node, node.right, value)
parent, node = find(None, self.root, value)
if node is None:
return
if node.left is None and node.right is None:
if node == self.root:
self.root = None
else:
if parent.left == node:
parent.left = None
else:
parent.right = None
elif node.left is None:
if node == self.root:
self.root = node.right
else:
if parent.left == node:
parent.left = node.right
else:
parent.right = node.right
elif node.right is None:
if node == self.root:
self.root = node.left
else:
if parent.left == node:
parent.left = node.left
else:
parent.right = node.left
else:
successor_parent = node
successor = node.right
while successor.left:
successor_parent = successor
successor = successor.left
node.value = successor.value
if successor_parent.left == successor:
successor_parent.left = successor.right
else:
successor_parent.right = successor.right
上面的代码实现了二叉树的查找和删除功能,使用方法如下:
root = TreeNode(8,
TreeNode(3,
TreeNode(2),
TreeNode(6,
TreeNode(4),
TreeNode(7))),
TreeNode(10,
None,
TreeNode(14,
TreeNode(13))))
tree = BinaryTree(root)
print(tree) # 8 3 10 2 6 # # 14 # # # # # #
tree.delete(6)
print(tree) # 8 3 10 2 4 # # 14 13 # # # # #