首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >树模型的迭代打印

树模型的迭代打印
EN

Stack Overflow用户
提问于 2012-01-19 03:58:14
回答 2查看 511关注 0票数 0

我有一棵这样的节点树:

代码语言:javascript
复制
class Node:
    next        # the next node or None
    prev        # the previous node or None
    parent      # the parent or None
    children[]  # ordered list of child nodes
    columns[]   # a list of data. Currently only holdt the 
                # string representation of the node in the model.

因为我无法预先知道模型有多大,所以我得出结论,递归不是一种选择。我希望在内存中保留尽可能少的节点。这就是我的方法应该打印的内容:

代码语言:javascript
复制
- 0
-- 0:0
--- 0:0:0
--- 0:0:1
---- 0:0:1:0
---- 0:0:1:1
--- 0:0:2
-- 0:1
- 1

但这就是它要打印的:

代码语言:javascript
复制
- 0
-- 0:0
-- 0:1
-- 0
- 1
--- 0:0:0
--- 0:0:1
--- 0:0:2
-- 0:1
-- 0
- 1
--- 0:0:1
---- 0:0:1:0
---- 0:0:1:1
--- 0:0:2
-- 0
---- 0:0:1:0
---- 0:0:1:1
--- 0:0:2
---- 0:0:1:1
---- 0:0:1:1

下面是我写的代码:

代码语言:javascript
复制
def print_tree(from_path):
    nodelist = []
    root_node = model.get_iter(from_path)
    nodelist.append((root_node, 0)) # the second item in the tuple is the indentation

    while nodelist:
        node = nodelist[0][0]
        indent = nodelist[0][1]
        del(nodelist[0])
        print("{0} {1}".format("-" * indent, node.columns[0])) 

        if node.children:
            child = node.children[0]
            nodelist.append((child, indent +1))

            while child.next:
                nodelist.append((child.next, indent +1))
                child = child.next
        if node.next:
            next = node.next
            nodelist.append((next, indent))

任何帮助都是非常感谢的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-19 04:25:13

因为每个节点都有对其父节点的引用,我认为您可以遍历整个树,每次只保留一个节点。我在理解您的代码(特别是每个节点如何加载到内存)时遇到了一些困难,所以我将在伪代码中发布我的建议:

代码语言:javascript
复制
def visit(node,indent):
    # Load your node data
    print("{0} {1}".format("-" * indent, node.columns[0])) # Do something with your data
    # Unload your node data
    if len(node.children) > 0 :
        return (node.children[0], indent+1) # Visit the first child, if there is one
    while node.next is None: # If no sibling, your parent is done
        node = node.parent
        indent -= 1
        if node is None: # Root node reached, end the traversal
            return None
    return (node.next, indent) # Visit your next sibling, if there is one

cursor = (root_node, 0)
while cursor is not None:
    cursor = visit(*cursor)

如果节点本身必须动态加载(即nextprevparentchildren只包含指向另一个节点数据的路径,而不是对Node对象的引用),那么告诉我,我将更新答案(只需要稍微更改加载/卸载的位置)。当然,如果卸载只是把对象留给垃圾收集器,那就更容易了.

票数 2
EN

Stack Overflow用户

发布于 2012-01-19 05:05:56

正如mgibsonbr所指出的,由于要存储父指针,所以可以在只跟踪当前节点(及其缩进)的情况下迭代执行此操作:

代码语言:javascript
复制
def print_tree(from_path):

    node, indent = model.get_iter(from_path), 0

    while node:

        if indent:           # don't print the root
            print "-" * indent, node.columns[0]

        if node.children:    # walk to first child before walking to next sibling
            node = node.children[0]
            indent += 1
        elif node.next:      # no children, walk to next sibling if there is one
            node = node.next
        else:
            # no children, no more siblings: find closet ancestor w/ more siblings
            # (note that this might not be the current node's immediate parent)
            while node and not node.next:
                node = node.parent
                indent -= 1
            node = node and node.next            

通过将print行替换为yield indent, node,可以将其转换为生成器。

我不得不模拟一些测试数据来调试它。这是我的资料,以防其他人想玩。我认为根不能有兄弟姐妹(没有理由不能使用next并将数据存储在columns中,但是您可能希望缩进从1开始)。

代码语言:javascript
复制
class Node(object):
    def __init__(self, parent=None, sib=None, value=""):
        self.parent   = parent
        self.prev     = sib
        self.next     = None
        self.children = []
        self.columns  = [str(value)]
    def child(self, value):
        child = Node(self, None, value)
        if self.children:
            self.children[-1].next = child
            child.prev = self.children[-1]
        self.children.append(child)
        return child
    def sib(self, value):
        return self.parent.child(value)

class model(object):
    @staticmethod
    def get_iter(_):

        root = Node()

        root.child("0").child("0:0").child("0:0:0").sib("0:0:1") \
            .child("0:0:1:0").sib("0:0:1:0").parent.sib("0:0:2")
        root.children[0].child("0:1").parent.sib("1")

        return root
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8920837

复制
相关文章

相似问题

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