Python中的固定深度树

2024-09-20 06:46:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想实现一个具有固定深度的树结构,即在向leef节点添加子节点时,整个树结构应该“上移”。这也意味着几个根可以同时存在。参见下面的示例: alt text 在本例中,在迭代1中添加绿色节点,删除顶部节点(灰色),并使K=0处的两个蓝色节点和迭代1的根节点成为根节点。在

我如何着手实施这一点?在


Tags: 示例节点蓝色树结构绿色灰色本例leef
1条回答
网友
1楼 · 发布于 2024-09-20 06:46:46

存储每个节点及其父节点的引用。当您将一个节点作为子节点添加到其中时,在将其所有子节点中的父引用设置为None之后,遍历父节点(从要添加到的节点)并删除第三个节点。然后将已删除节点的子节点添加到树列表中。在

class Node(object):

    depth = 4

    def __init__(self, parent, contents):
        self.parent = parent
        self.contents = contents
        self.children = []


def create_node(trees, parent, contents):
    """Adds a leaf to a specified node in the set of trees.

    Note that it has to have access to the container that holds all of the trees so
    that it can delete the appropriate parent node and add its children as independent 
    trees. Passing it in seems a little ugly. The container of trees could be a class
    with this as a method or you could use a global list. Or something completely
    different. The important thing is that if you don't delete every reference to the
    old root, you'll leak memory.
    """
    parent.children.append(Node(parent, contents))

    i = 0:
    L = Node.depth - 1
    while i < L:
        parent = parent.parent
        if not parent:
            break
        i += 1
    else:
        for node in parent.children:
            node.parent = None
        trees.extend(parent.children)
        i = trees.find(parent)
        del trees[i]

相关问题 更多 >