Sunday, 15 March 2015

Week 8 (Week 7 Impressions)

Last week we continued our work on assignment 2 and continued learning more about trees.  Instead of our previous tree examples with self.children, we focused on a special kind of tree, binary tree nodes (BTNode).  BTNodes still have __repr__, __str__, and __eq__ methods as usual but instead of having self.children, these nodes only have (at most) two children: self.left and self.right.  For binary trees, data must be comparable, and all data in self.left must be less than node's data and all data in self.right must be greater than node's data.  Binary trees are used because they are efficient when searching along a single path.  These trees can also be used to represent arithmetic expressions, i.e ((3*4)-7)/2.  This would have the root node = '/', self.left = -, self.left.left = *, self.left.left.left = 3, self.left.left.right = 4, self.left.right = 7, and self.right = 2.  To evaluate such a tree, return self.data if the tree is just a leaf, or evaluate the left side and right side separately using python's eval and combine left and right.

Here you can see two important methods for binary tree nodes.  The difference between the two is that bst_contains checks whether the wanted value is greater or less than the node value, before calling itself on the node's left or right child.
def contains(node, value):
    ''' (BTNode, object) -> value

    Return whether tree rooted at node contains value.

    >>> contains(None, 5)
    False
    >>> contains(BTNode(5, BTNode(7), BTNode(9)), 7)
    True
    '''
    if node is None:
        return False
    else:
        return (node.data == value or 
                contains(node.left, value) or 
                contains(node.right, value))


def bst_contains(node, value):
    ''' (BTNode, object) -> value

    Return whether tree rooted at node contains value.

    Assume node is the root of a BST.

    >>> contains(None, 5)
    False
    >>> contains(BTNode(7, BTNode(5), BTNode(9)), 5)
    True
    '''
    assert node is None or isinstance(node, BTNode), (
        'Not a BTNode: {}'.format(node))
    if node is None:
        return False
    elif node.data > value:
        return bst_contains(node.left)
    elif node.data < value:
        return bst_contains(node.right)
    else:
        return True

We also looked at the recursive functions inorder, preorder, and postorder for visiting tree nodes.
Inorder visits the left tree, the node, then the right tree.  Preorder visits the node, the left tree, then the right tree, and postorder visits the left tree, the right tree, then the node.

No comments:

Post a Comment