首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能从该BST递归删除节点?

问不能从该BST递归删除节点?
EN

Stack Overflow用户
提问于 2014-04-29 15:07:03
回答 1查看 97关注 0票数 1

Python新手。已尝试实施BST。它可以工作,除了我似乎不能递归地删除其中的节点:

代码语言:javascript
复制
# 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()方法上,但我看不出是什么问题。

EN

回答 1

Stack Overflow用户

发布于 2014-04-29 18:16:57

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

对象永远不会显式销毁;但是,当它们变得不可访问时,它们可能会被垃圾回收。允许实现推迟或完全省略垃圾收集--垃圾收集是如何实现的,这是一个实现质量问题,只要没有收集到仍然可访问的对象。

为了让你的代码工作--你不需要递归地销毁。在Python中可以做到:

代码语言:javascript
复制
# 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'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23357806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档