class BTNode:
'''Binary Tree node.'''
def __init__(self, data, left=None, right=None):
''' (BTNode, object, BTNode, BTNode) -> NoneType
Create BTNode (self) with data and children left and right.
'''
self.data, self.left, self.right = data, left, right
Professor Heap led us to implement a function for the BTNode class, which is called evaluate, through exercise. Evaluate makes calculation based on the data of BTNode using recursion. I found it easier than writing functions for tree, or maybe I am just getting used to it.
def evaluate(b):
''' (BTNode) -> float
Evaluate the expression rooted at b. If b is a leaf,
return its float data. Otherwise, evaluate b.left and
b.right and combine them with b.data.
Assume: -- b is a non-empty binary tree
-- interior nodes contain data in {'+', '-', '*', '/'}
-- interior nodes always have two children
-- leaves contain float data
>>> b = BTNode(3.0)
>>> evaluate(b)
3.0
>>> b = BTNode('*', BTNode(3.0), BTNode(4.0))
>>> evaluate(b)
12.0
'''
if b.left is None and b.right is None:
return b.data
else:
return eval(str(evaluate(b.left)) +
b.data +
str(evaluate(b.right)))
We also learned binary search tree (BST), which is a special kind of binary tree. It needs to fulfill the restriction that self.left.data < self.data < self.right.data. We then implemented more functions about binary tree and BST in the lab.
Moreover, I started assignment 2 in week 7. I found an awesome teammate, and he made the whole process joyful and relaxed, even though this assignment is hard in some way. I will write in more details next week.

No comments:
Post a Comment