Monday, 9 March 2015

week 8

The new concept of Binary Search Trees is being introduced in lecture this week. BST is the special tree category as structure is different than normal tree. Each BST node at most has two children. Each value that is smaller than the root is contained in the left sub-tree while each value larger than the root is contained in the right sub-tree. We can use binary search method in BST. One of the advantage of BST is that binary search cuts its search steps in half every time it does not find its desired value, the binary search is more efficient and quicker. 


def find(node, data):
    ''' (BTNode, object) -> BTNode

    Return the BTNode containing data, or else None.

    >>> b = BTNode(5, BTNode(4))
    >>> find(b, 7) is None
    True
    >>> find(b, 4)
    BTNode(4, None, None)
    '''
    if not node or node.data == data:
        return node
    else:
        return (find(node.left, data) if (data < node.data)
                else find(node.right, data))
As code shows above, BST will search the specific value. If the value less than node, then it cuts right tree and only search left tree. Reversely, it establishes as well. 

In addition, there are three approach of BST: preorder, postorder and inorder. These three orders has been tested on term test 2.

No comments:

Post a Comment