Skip to content

Instantly share code, notes, and snippets.

@buchanae
Last active October 13, 2015 18:27
Show Gist options
  • Save buchanae/4237556 to your computer and use it in GitHub Desktop.
Save buchanae/4237556 to your computer and use it in GitHub Desktop.
Representing a tree and doing a pre-order traversal
from __future__ import print_function
# The tree:
# a
# b c
# d e f g
# h i j k l m n o
graph = {
'a': ['b', 'c'],
'b': ['d', 'e'],
'c': ['f', 'g'],
'd': ['h', 'i'],
'e': ['j', 'k'],
'f': ['l', 'm'],
'g': ['n', 'o'],
}
def trace(start, graph):
out = [start]
try:
for key in graph[start]:
sub = trace(key, graph)
out.extend(sub)
except KeyError:
pass
return out
if __name__ == '__main__':
print(trace('a', graph))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment