Last active
June 18, 2016 16:42
-
-
Save xiezhenye/423c2283b31fd2011095507978d1c89e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, name, children): | |
self.name = name | |
self.children = children | |
tree = Node(1, [ | |
Node(2, [ | |
Node(3, [ | |
Node(4, []), | |
Node(5, [ | |
Node(6,[]) | |
]), | |
]), | |
Node(7, [ | |
Node(8, []), | |
Node(9, []), | |
]), | |
]), | |
Node(10, [ | |
Node(11, []), | |
Node(12, [ | |
Node(13, []), | |
Node(14, [ | |
Node(15, []), | |
]), | |
]) | |
]), | |
Node(16, []), | |
]) | |
def iterate(tree): | |
stack = [] | |
stack.append(iter([tree])) | |
while stack: | |
iterator = stack[-1] | |
try: | |
node = iterator.next() | |
yield node | |
stack.append(iter(node.children)) | |
except: | |
stack.pop() | |
for node in iterate(tree): | |
print node.name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment