无法以递归方式从此BST中删除节点?

时间:2014-04-29 07:07:03

标签: python binary-search-tree

Python新手。试图实施BST。它的工作原理,除了我似乎无法从递归中删除节点的事实:

# in class BST
def destroy(self):
    if self.left:
        self.left.destroy()
    if self.right:
        self.right.destroy()
    self = None

# in main
root = BST(60)
root.insert(40) # inserts 40 at 60's left
root.insert(50) # inserts 50 at 40's right

print root.right # prints None because nothing's there
print root.left.right # prints 50 
root.left.destroy() # is supposed to remove 40 and 50 from the tree
print root.left.right # prints 50, even though it should be None now...

问题必须是destroy()方法,但我看不出问题所在。

1 个答案:

答案 0 :(得分:0)

在Python中,您不需要显式管理内存; here is a link to another SO question具有相同的主要要点。来自the Python docs

  

永远不会明确销毁对象;然而,当它们变得无法到达时,它们可能被垃圾收集。允许实现推迟垃圾收集或完全省略它 - 实现垃圾收集的实现质量问题,只要没有收集到仍然可以访问的对象。

要使代码正常工作 - 您不需要递归销毁。在Python中可以做到:

# in main
print root.right # prints None because nothing's there
print root.left.right # prints 50 
root.left = None
print root.left.right # AttributeError:'NoneType' object has no attribute 'right'
相关问题