<
2 1 6 9 4 = 8
Keys are assumed to come from a total order. New operations: closestKeyBefore(k) closestElemBefore(k) closestKeyAfter(k) closestElemAfter(k)
1 Binary Search Trees 2
>
Binary Search Trees
Binary Search (§3.1.1)
Binary search performs operation findElement(k) on a dictionary implemented by means of an array-based sequence, sorted by key similar to the high-low game at each step, the number of candidate items is halved terminates after O(log n) steps
Lookup Table (§3.1.1)
A lookup table is a dictionary implemented by means of a sorted sequence
We store the items of the dictionary in an array-based sequence, sorted by key We use an external comparator for the keys
Example: findElement(7)
0 1 1 1 1 3 3 4 4 4 5 5 5 7 7 8 9 9 9 9 11 11 11 11 14 14 14 14 16 16 16 16 18 18 18 18 3 19
Performance: m 8 8 8
l
0
h
19 19 19
l
0 0
m
3 3
h
7
findElement takes O(log n) time, using binary search insertItem takes O(n) time since in the worst case we have to shift n/2 items to make room for the new item removeElement take O(n) time since in the worst case we have to shift n/2 items to compact the items after the removal
l
4
m
5
h
7
l=m =h
Binary Search Trees
The lookup table is effective only for dictionaries of small size or for dictionaries on which searches are the most common operations, while insertions and removals are rarely performed (e.g., credit card authorizations)
Binary Search Trees 4
Binary Search Tree (§3.1.2)
A binary search tree is a binary tree storing keys (or key-element pairs) at its internal nodes and satisfying the following property:
Let u, v, and w be three nodes such that u is in the left subtree of v and w is in the right subtree of v. We have key(u) ≤ key(v) ≤ key(w)
Search (§3.1.3)
An inorder traversal of a binary search trees visits the keys in increasing order
6 2 1 4 8 9 Algorithm findElement(k, v) To search for a