39A. Tables


Tables

We have used binary search trees to represent sets of integers. But they can do more than that.

From the perspective of the data, all that is needed to implement binary search trees is an ordering (<, >, etc.), and it is easy to generalize binary search trees to a set of strings, as set of real numbers, or a set of widgets, as long as there is a way to ask whether one widget is less than another.

But we can do even more. Suppose each node contains two values, a key and an item. Think of a telephone book. The key is a person's name and the item is that person's telephone number. All the operations (lookup, insert, remove) are based on the keys, carrying the item along in each node. Lookup can return the item associated with a given key, and insert can insert a pair (k, x) of a key k and an associated item x.

So binary search trees provide a way to implement tables so that all operations (lookup, insert, remove) take time Θ(log(n)) in the worst case, where n is the number of keys in the table.

Can we do better? We explore that on the next page.