2015年3月21日星期六

Week 8


In week 7 we learned about another abstract data type, binary tree. Binary tree is a kind of tree with special property.
(binary tree)


(binary search tree)
Each node in a binary tree has at most two children, left child and right child. There is a special kind of binary tree called binary search tree. The value of its left child is smaller than the value of the current node, and the value of its right child is bigger than the value of the current node. Because of this property, we can search for data efficiently in a binary search tree. For example, if you want to know if a binary search tree contains a value:
def bst_contains_v1(node, v):
    ''' (BTNode, v) -> bool
   
    Return whether the binary tree rooted at node contains v.

    Assumption: node is the root of a binary search tree.
     '''
    if v == None:
        return False
    elif v == node.data:
        return True
    elif v < node.data:
        return contains(node.left, v)
    else:
        return contains(node.right, v)   
If you want to search for a value in a binary search tree, you don’t need to search through the entire tree. You can compare the value with the value of current node. If the value is bigger than the value of current node, you don’t need to compare it with the nodes that are rooted at its left children.

We had an assignment due the following week, my teammates and I all worked very hard. Using recursion in our assignment is really interesting and challenging.

没有评论:

发表评论