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()方法上,但我看不出是什么问题。
发布于 2014-04-29 18:16:57
在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'https://stackoverflow.com/questions/23357806
复制相似问题