因此,假设如下:
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)