Created
February 26, 2011 14:06
-
-
Save rik0/845224 to your computer and use it in GitHub Desktop.
This file contains 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
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