Created
May 27, 2012 10:19
-
-
Save joneskoo/2803193 to your computer and use it in GitHub Desktop.
Walk a binary tree
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
#encoding: utf-8 | |
class Node: | |
left = None | |
right = None | |
parent = None | |
key = None | |
def __init__(self, key): | |
self.key = key | |
def walk(self, code='', f=None): | |
self.code = code | |
if f: | |
f(self) | |
if self.left: | |
self.left.walk(code + '0', f) | |
if self.right: | |
self.right.walk(code + '1', f) | |
class Tree: | |
root = None | |
def walk(self, f=None): | |
self.root.walk(f=f) | |
def main(): | |
def _f(node): | |
print "%-04s '%s'" % (node.code, node.key) | |
t = Tree() | |
t.root = Node('juuri') | |
t.root.left = Node('eka') | |
t.root.left.right = Node('toka') | |
t.root.left.left = Node('kolmas') | |
t.root.right = Node(u'neljäs') | |
t.root.right.left = Node('viides') | |
t.walk(f=_f) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment