如何在Python中修剪子树
我(仍然)正在处理 Python 程序中的树结构。 树中的每个节点都有一个字典“children”,其键保存弧信息,值 是子节点。 (每个节点都有一个(parent,parent_arc)对,其中parent是其父节点,parent_arc是父节点链接该节点的弧。)
现在我想修剪一棵子树,其根是节点的子节点N. 假设这个孩子是 N.children[a]。
del N.children[a] 根本不会释放子树占用的内存。我是否必须实现一种方法来删除子树中的每个节点?我该怎么做?我是否需要重新定义节点类以实现高效的子树修剪?
谢谢你!
I am (still) dealing with a tree structure in a Python program.
Each node in a tree has a dictionary "children", whose keys hold arc information, and values
are the child nodes. (And each node has a (parent, parent_arc) pair, where parent is its parent node and parent_arc is the arc by which the parent node link this node.)
Now I want to prune a subtree, whose root is a child of a node N. Say the child is N.children[a].
del N.children[a] simply won't release the memory occupied by the subtree. Do I have to implement a method to delete every node in the subtree? How can I do this ? Do I need to re-define the node class for efficient subtree pruning?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当A->时B和B-> A 你有参考周期。解决这个问题的一个好方法是让子级使用弱引用来指向父级。像这样的事情:
现在,该节点没有与其父节点的直接链接,当您删除子节点时,它确实会消失*。 (您可能需要对parent_arc使用相同的方法。)
*请注意,即使Python在不存在引用循环的情况下会更快地释放对象,但它可能不会将该内存返还给操作系统。
When A -> B and B -> A you have reference cycles. A good way to get around that is to have the children use weak references to point back to the parent. Something like this:
Now, the node does not have a direct link to its parent, and when you delete the child it really will go away*. (You may need to use the same method for the parent_arc.)
*Note that even though Python will release the objects more quickly if no reference cycles exist, it may not give that memory back to the OS.