我用Python编写的一个树类,但我有它 创造迭代问题,我希望能够做到递归迭代(在Python树)
phonebook = MyTree()
# Build up tree
for node in phonebook:
print "%s: %s" % (node.key(), node.data())
但它不工作(说生成器对象没有key()和data())。 My Tree类的__iter__
函数返回我创建的迭代器类。这是我到目前为止(我知道这是错误的,它不工作,因为它返回一个生成器对象,因为这是什么产量,我想它记住它在递归中的位置虽然..我不能使用返回) 。基本上我只想返回节点。
class TreeIterator():
def __init__(self, root, size):
self._current = root
self._size = size
self.num_visited = 0
def __iter__(self):
return self
def next(self):
return self._next(self._current)
def _next(self, curr):
self.num_visited = self.num_visited + 1
if self.num_visited == self._size:
raise StopIteration
if curr.left is not None and curr.left is not TreeNode.NULL:
yield self._next(curr.left)
yield curr
if curr.right is not None and curr.right is not TreeNode.NULL:
yield self._next(curr.right)
这工作,我真的见过这之前,但我不能得到它的工作。你能解释为什么这个工作吗?对于self_next(curr.left)中的x,我仍然不太明白。 – robev 2010-12-16 16:45:27