开发者

How to prune subtree in python

开发者 https://www.devze.com 2023-03-31 02:02 出处:网络
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

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 n开发者_开发知识库odes. (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!


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:

import weakref
class Node():
    parent = None
    child = None
    @property
    def parent(self):
        parent = self._parent()
        if parent is not None:
            return parent
        raise ValueError("parent has been deleted")
    @parent.setter     # python 2.6+
    def parent(self, parent):
        self._parent = weakref.ref(parent)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消