I've written a Tree class in Python but I'm having issues creating in iterator for it I want to be able to do
phonebook = MyTree()
# Build up tree
for node in phonebook:
print "%s: %s" % (node.key(), node.data())
But it's not working (says generator object doesn't have key() and data()). My Tree class's __iter__ function returns an iterator class I've created. Here's what I have so far (I know it's wrong and it's not working as it's returning a generator object, since that's what yield does, I want it to remember where it was in the recursion though..so I can't use return) . Basically I just want to return the nodes inorder.
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)