下面是我正在处理的程序,它创建了一个树,然后可以从树中删除节点。我无法理解删除节点是如何工作的,我正在寻找一些指导。目前我的代码用最左边的叶子替换了节点,但我试图让它删除整个事情,就像它从来没有。这是我遇到困惑的地方。有人可以解释一下吗?
def remove(self, data):
if self.root and self.root.data == data: # special case for removing the root
self.root = self.root.delete()
return
else: # general case, removing a child node of some parent
parent = self.root
while parent:
if data < parent.data:
child = parent.left
if child and child.data == data:
if child.left == None and child.right == None:
parent.left = None
return
if child.left == None:
parent.left = child.right
child = None
return
if child.right == None:
parent.left = child.left
child = None
return
left_most = child
while left_most.left != None:
second_left = left_most
left_most = left_most.left
child.data = left_most.data
second_left = None
return
parent = child
else:
child = parent.right
if child and child.data == data:
if child.left == None and child.right == None:
parent.right = None
return
if child.left == None:
parent.right = child.right
child = None
return
if child.right == None:
parent.right = child.left
child = None
return
left_most = child
while left_most.left != None:
second_left = left_most
left_most = left_most.left
child.data = left_most.data
second_left = None
return
parent = child
答案 0 :(得分:1)
家庭作业这个问题来自链接到一个网页,该网页显示了如何进行删除。也许你应该发布整个作业,以便你可以回答你的问题。