def remove(self,node):
def removerec(aroot,node):
if node < aroot.item:
if aroot.left == None:
return print("Does not exist")
return removerec(aroot.left,node)
elif node > aroot.item:
if aroot.right == None:
return print("Does not exist")
return removerec(aroot.right,node)
else: # When aroot.item = node
if aroot.left == None and aroot.right == None:
aroot = None
return
elif aroot.left == None and aroot.right != None:
aroot = aroot.right
return
elif aroot.right == None and aroot.left != None:
aroot = aroot.left
return
else:
if self.countChildren(aroot.left.item) > self.countChildren(aroot.right.item):
test = aroot.left
while test.right != None:
test = test.right
aroot.item = test.item
return removerec(aroot.left,test.item)
else:
test = aroot.right
while test.left != None:
test = test.left
aroot.item = test.item
return removerec(aroot.right,test.item)
if not self.exists(node):
return "Does not exist"
else:
return removerec(self.root,node)
问题在于
if aroot.left == None and aroot.right == None:
aroot = None
不会从树中删除节点。当要删除的节点有两个子节点时,它会成功将其更改为右子节点的最左侧子节点或左子节点的最右侧子节点,但无法删除其接收到的值的节点。我一直在测试,似乎aroot更改为None(已删除),但不是树中的节点。我可能会遗漏一些明显的东西,但会得到一些帮助。