python – 使用生成器在BST上执行inorder树遍历

所以给出以下内容:

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

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

x只包含根节点,为什么?

这是完整的代码;请注意,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)只创建生成器对象,它实际上并不运行它.您需要迭代并生成每个子生成器生成的值:

# 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

通过在Python 3.3中引入new syntax,这变得更加清晰:

# Python 3
def inorder(t):
    if t:
        yield from inorder(t.left)
        yield t.key
        yield from inorder(t.right)
点赞