This kind of iterators (using closures) are called generators in python.
Generators are functions, using 'yield' keyword instead of 'return'. When yield is encountered, the respective value is returned, but the execution state of the function is suspended, until the next value is required.
So, you can just implement a tree-traversal function, using 'yield' instead of 'return', and your goal will be accomplished.
They are very easy to design:
# Simple tree definition
class Tree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
# In-order lazy iterator (aka generator)
def inorder(tree):
if tree is not None:
for x in inorder(tree.left):
yield x
yield tree.data
for x in inorder(tree.right):
yield x
# Reverse in-order lazy iterator
def rev_inorder(tree):
if tree is not None:
for x in rev_inorder(tree.right):
yield x
yield tree.data
for x in rev_inorder(tree.left):
yield x
# Construct a tree
n1 = Tree(1)
n2 = Tree(2)
n3 = Tree(3) # 7
n4 = Tree(4) # / \
n5 = Tree(5, n1, n2) # 5 6
n6 = Tree(6, n3, n4) # / \ / \
n7 = Tree(7, n5, n6) # 1 2 3 4
for i in inorder(n7):
print i,
print
for i in rev_inorder(n7):
print i,
print
Output:
1 5 2 7 3 6 4
4 6 3 7 2 5 1
To manually iterate, use:
gen = rev_inorder(n7)
print gen.next() # Output 4
print gen.next() # Output 6