我正在尝试使preOrder递归,以便可以执行以下操作:
给出一棵树[2,1,3]的数组表示形式(该程序实际上采用了TreeNode,特别是TreeNode(2)
x = preOrder(root)
print x.next() # 1
print x.next() # 2
print x.next() # 3
但是给出以下代码,我只能调用x.next()一次,然后在第一次迭代后什么也不会返回。
def preOrder(root):
if root is not None:
preOrder(root.left)
self.lChild = root.left
self.rChild = root.right
yield root.val
preOrder(root.right)
我该如何解决?
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
答案 0 :(得分:1)
您可以这样解决它:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return str(self.val)
three = TreeNode(3)
one = TreeNode(1)
two = TreeNode(2)
two.left = one
two.right = three
def pre_order(root):
if root is not None:
yield from pre_order(root.left)
yield root.val
yield from pre_order(root.right)
for e in pre_order(two):
print(e)
输出
1
2
3
基本上,您还需要从递归调用中屈服。鉴于您正在使用Python 2.7,请参见: