简体   繁体   English

使用生成器在 BST 上执行中序树遍历

[英]Using generators to perform an inorder tree traversal on a BST

So given the following:所以给出以下内容:

def inorder(t):
    if t:
        inorder(t.left)
        yield t.key
        inorder(t.right)

x = [ n for n in inorder(r) ]

x only contains the root node, why? x只包含根节点,为什么?

Here's the full code;这是完整的代码; note that the BST implementation is correct, it's the inorder() implementation with generators that is somehow wrong.请注意,BST 实现是正确的,它是带有生成器的inorder()实现在某种程度上是错误的。

class STree(object):
    def __init__(self, value):
        self.key = value
        self.left = None
        self.right = None

def insert(r, node):
    if node.key < r.key:
        if r.left is None:
            r.left = node
        else:
            insert(r.left, node)
    else:
        if r.right is None:
            r.right = node
        else:
            insert(r.right, node)

def inorder(t):
    if t:
        inorder(t.left)
        yield t.key
        inorder(t.right)


r = STree(10)
insert(r, STree(12))
insert(r, STree(5))
insert(r, STree(99))
insert(r, STree(1))

tree = [ n for n in inorder(r) ]
print tree

inorder(t.left) only creates the generator object, it doesn't actually run it. inorder(t.left)只创建生成器对象,它实际上并没有运行它。 You need to actually yield all the values produced by each of the sub-generators, like so:您需要实际yield每个子生成器产生的所有值,如下所示:

def inorder(t):
    if t:
        yield from inorder(t.left)
        yield t.key
        yield from inorder(t.right)

Note that the yield from convenience syntax was only introduced in Python 3.3 so if you're using an older version you'll have to iterate over the sub-generators explicitly:请注意, yield from便捷语法仅在Python 3.3中引入,因此如果您使用的是旧版本,则必须显式地迭代子生成器:

# Python 2
def inorder(t):
    if t:
        for key in inorder(t.left):
            yield key
        yield t.key
        for key in inorder(t.right):
            yield key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM