Skip to content

Instantly share code, notes, and snippets.

@xiezhenye
Last active June 18, 2016 16:42
Show Gist options
  • Save xiezhenye/423c2283b31fd2011095507978d1c89e to your computer and use it in GitHub Desktop.
Save xiezhenye/423c2283b31fd2011095507978d1c89e to your computer and use it in GitHub Desktop.
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