Skip to content

Instantly share code, notes, and snippets.

@rik0
Created February 26, 2011 14:06
Show Gist options
  • Save rik0/845224 to your computer and use it in GitHub Desktop.
Save rik0/845224 to your computer and use it in GitHub Desktop.
import collections
Node = collections.namedtuple('Node', 'value left right')
def make_node(value, left=None, right=None):
return Node(value, left, right)
def preorder(tree):
stack = [tree]
while stack:
current = stack.pop()
yield current.value
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
example = make_node(0,
left=make_node(6,
left=make_node(3),
right=make_node(1, right=make_node(4))),
right=make_node(8, left=make_node(7)))
for node in preorder(example):
print node
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment