http://openbookproject.net/thinkcs/python/english3e/trees.html
class Tree:
def __init__(self, data, left=None, right=None):
self.cargo = data
self.left = left
self.right = right
def __str__(self):
return "{}".format(self.cargo)
left = Tree(2)
right = Tree(3)
tree = Tree(1, left, right)
tree1 = Tree(10, Tree(20), Tree(30))
print(tree)
1
print(tree1)
10
def findSum(tree):
if not tree:
return 0
return tree.cargo + findSum(tree.left) + findSum(tree.right)
findSum(tree)
6
findSum(tree1)
60
applications:
three ways to traverse trees: pre-order, in-order and post-order
expression = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3)))
def preorder(tree):
if not tree:
return
print(tree.cargo, end=' ')
preorder(tree.left)
preorder(tree.right)
preorder(expression)
+ 1 * 2 3
def inorder(tree):
if not tree:
return
inorder(tree.left)
print(tree.cargo, end=' ')
inorder(tree.right)
inorder(expression)
1 + 2 * 3
def inorderIndented(tree, level=0):
if not tree:
return
inorderIndented(tree.right, level+1)
print(' '*level + str(tree.cargo))
inorderIndented(tree.left, level+1)
inorderIndented(expression)
3 * 2 + 1
def postorder(tree):
if not tree:
return
postorder(tree.left)
postorder(tree.right)
print(tree.cargo, end=' ')
postorder(expression)
1 2 3 * +
def get_token(token_list, expected):
if token_list[0] == expected:
del token_list[0]
return True
return False
# handles operands
def get_number(token_list):
x = token_list[0]
if not isinstance(x, int):
return None
del token_list[0]
return Tree(x, None, None) # leaf node
token_list = [9, 11, 'end']
x = get_number(token_list)
postorder(x)
9
print(token_list)
[11, 'end']
def get_product(token_list):
a = get_number(token_list)
if get_token(token_list, '*'):
b = get_number(token_list)
return Tree('*', a, b)
return a
token_list = [9, '*', 11, 'end']
tree = get_product(token_list)
postorder(tree)
9 11 *
token_list = [9, '+', 11, 'end']
tree = get_product(token_list)
postorder(tree)
9
# adapt the function for compound product such as 3 * (5 * (7 * 9))
def get_product(token_list):
a = get_number(token_list)
if get_token(token_list, '*'):
b = get_product(token_list)
return Tree('*', a, b)
return a
token_list = [2, "*", 3, "*", 5 , "*", 7, "end"]
tree = get_product(token_list)
postorder(tree)
2 3 5 7 * * *
# a sum can be a tree with + at the root, a product on the left, and a sum on the right.
# Or, a sum can be just a product.
def get_sum(token_list):
a = get_product(token_list)
if get_token(token_list, "+"):
b = get_sum(token_list)
return Tree("+", a, b)
return a
token_list = [9, "*", 11, "+", 5, "*", 7, "end"]
tree = get_sum(token_list)
postorder(tree)
9 11 * 5 7 * +
# handle parenthesis
def get_number(token_list):
if get_token(token_list, "("):
x = get_sum(token_list) # Get the subexpression
get_token(token_list, ")") # Remove the closing parenthesis
return x
else:
x = token_list[0]
if not isinstance(x, int):
return None
del token_list[0]
return Tree(x, None, None)
# 9 * (11 + 5) * 7
token_list = [9, "*", "(", 11, "+", 5, ")", "*", 7, "end"]
tree = get_sum(token_list)
postorder(tree)
9 11 5 + 7 * *
# handle parenthesis
def get_number(token_list):
if get_token(token_list, "("):
x = get_sum(token_list) # Get the subexpression
if not get_token(token_list, ")"): # Remove the closing parenthesis
raise ValueError('Missing close parenthesis!')
return x
else:
x = token_list[0]
if not isinstance(x, int):
return None
del token_list[0]
return Tree(x, None, None)
token_list = [9, "*", "(", 11, "+", 5, "*", 7, "end"]
tree = get_sum(token_list)
postorder(tree)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-55-4140410c22b2> in <module>() 1 token_list = [9, "*", "(", 11, "+", 5, "*", 7, "end"] ----> 2 tree = get_sum(token_list) 3 postorder(tree) <ipython-input-47-840e89a9fc06> in get_sum(token_list) 2 # Or, a sum can be just a product. 3 def get_sum(token_list): ----> 4 a = get_product(token_list) 5 if get_token(token_list, "+"): 6 b = get_sum(token_list) <ipython-input-45-dc9c6c17cd73> in get_product(token_list) 2 a = get_number(token_list) 3 if get_token(token_list, '*'): ----> 4 b = get_product(token_list) 5 return Tree('*', a, b) 6 return a <ipython-input-45-dc9c6c17cd73> in get_product(token_list) 1 def get_product(token_list): ----> 2 a = get_number(token_list) 3 if get_token(token_list, '*'): 4 b = get_product(token_list) 5 return Tree('*', a, b) <ipython-input-54-e5973ec52d85> in get_number(token_list) 4 x = get_sum(token_list) # Get the subexpression 5 if not get_token(token_list, ")"): # Remove the closing parenthesis ----> 6 raise ValueError('Missing close parenthesis!') 7 return x 8 else: ValueError: Missing close parenthesis!