Skip to content

Instantly share code, notes, and snippets.

@harushimo
Created November 29, 2012 01:05
Show Gist options
  • Save harushimo/4166008 to your computer and use it in GitHub Desktop.
Save harushimo/4166008 to your computer and use it in GitHub Desktop.
binary tree
#!/usr/bin/python
#Building the trees
class Tree(object):
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
return str(self.cargo)
#Traversing through the tree
def total(self):
if self == None: return 0
return self.total(self.left) + self.total(self.right) + self.cargo
#Traversing through the tree using preorder
def print_tree(tree):
if tree == None: return
print tree.cargo
print_tree(tree.left)
print_tree(tree.right)
#Allocating the child nodes
left = Tree(2)
right = Tree(3)
tree = Tree(1, left, right)
#tree = Tree(1, Tree(2), Tree(3))
print_tree(tree)
Error Messages:
File "./tree.py", line 30, in <module>
print print_tree(tree)
NameError: name 'print_tree' is not defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment