Tuesday, 31 March 2015

Week 9: More Binary Search Trees

This week we worked on more binary search trees focusing on manipulation of the data within the binary search tree. We had very limited exposure to the material that week due to the test but it certainly is something new. To insert or delete nodes from a binary search tree, which has a rather rigid format, and keeping the structure intact. Whereas the insert method is fairly simple to grasp in terms of coding, the delete method I find is much more difficult.

def delete(node, data):
    ''' (BTNode, data) -> BTNode

    Delete, if it exists, node with data and return resulting tree.

    >>> b = BTNode(8)
    >>> b = insert(b, 4)
    >>> b = insert(b, 2)
    >>> b = insert(b, 6)
    >>> b = insert(b, 12)
    >>> b = insert(b, 14)
    >>> b = insert(b, 10)
    >>> b = delete(b, 12)
    >>> print(b)
            14
        10
    8
            6
        4
            2
    <BLANKLINE>
    '''
    # Algorithm for delete:
    # 1. If this node is None, return that
    # 2. If data is less than node.data, delete it from left child and
    #     return this node
    # 3. If data is more than node.data, delete it from right child
    #     and return this node
    # 4. If node with data has fewer than two children,
    #     and you know one is None, return the other one
    # 5. If node with data has two non-None children,
    #     replace data with that of its largest child in the left subtree,
    #     and delete that child, and return this node
    return_node = node
    if node is None:
        pass
    elif node.data > data:
        node.left = delete(node.left, data)
    elif node.data < data:
        node.right = delete(node.right, data)
    elif node.left is None:
        return_node = node.right
    elif node.right is None:
        return_node = node.left
    else:
        node.data = _find_max(node.left).data
        node.left = delete(node.left, node.data)
    return return_node


    Here is the solution for this week's exercises. Conceptually, it is easy to grasp. If data satisfies the conditions for left and right nodes, delete those nodes. The difficult part comes when you have to rearrange the binary search tree to maintain the structure. You must check children and make sure that they are in the right spots while maintaining the recursive structure. I find that the more elements you add to a recursive code, the more likely it is to fail or run into errors. I certainly will need to practice more on binary search trees before the final!

No comments:

Post a Comment