Skip to content

Instantly share code, notes, and snippets.

@swaroopch
Created June 23, 2010 05:59
Show Gist options
  • Save swaroopch/449561 to your computer and use it in GitHub Desktop.
Save swaroopch/449561 to your computer and use it in GitHub Desktop.
Implement a tree iterator without using a stack
def eachnode(tree, n=0):
if n == len(tree):
raise StopIteration
yield tree[n] ## The method of access is specific to the data structure
for subnode in eachnode(tree, n+1):
yield subnode
if __name__ == '__main__':
tree = [10,20,30] ## Assuming array for test purposes, can be a real tree.
for node in eachnode(tree):
print node
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment