代码之家  ›  专栏  ›  技术社区  ›  Alex Recarey

如何使用生成器遍历树的叶子

  •  0
  • Alex Recarey  · 技术社区  · 16 年前

    问题是:

    我有一个 trie

    在所有trie中,每个节点上的叶子数是可变的,每个值的键实际上是由到达每个叶子所需的路径组成的。

    我试图使用生成器遍历树的后序,但我不能让它工作。我做错什么了?

    class Node():
        '''Each leaf in the trie is a Node() class'''
        def __init__(self):
            self.children = {}
            self.value = 0
    
    class Trie():
        '''The Trie() holds all nodes and can return a list of their values'''
        def __init__(self):
            self.root = Node()
        def add(self, key, value):
            '''Store a "value" in a position "key"'''
            node = self.root
            for digit in key:
                number = digit
                if number not in node.children:
                    node.children[number] = Node()
                node = node.children[number]
            node.value = value
        def __iter__(self):
            return self.postorder(self.root)
        def postorder(self, node):
            if node:
                for child in node.children.values():
                    self.postorder(child)
                # Do my printing / job related stuff here
                if node.value > 0:
                    yield node.value
    

    示例用法:

    >>trie = Trie()
    >>trie.add('foo', 3)
    >>trie.add('foobar', 5)
    >>trie.add('fobaz', 23)
    
    >>for key in trie:
    >>....print key
    >>
    3
    5
    23
    

    注意:我省略了代码块中的换行符,以便更轻松地复制粘贴。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Wai Yip Tung    16 年前

    改变

    self.postorder(child)
    

    到

    for n in self.postorder(child):
        yield n
    

    似乎能成功。

    P.S.这是非常有帮助的,你留下的空白线,便于切割和粘贴: