38A. Binary Search Trees

We have seen that a set of integers can be stored in an array in ascending order, and that binary search allows lookup in the array in time O(log(n)) where n is the size of the set. But we also noticed that using an array does not appear to allow values to be inserted or removed efficiently, and we set a goal of finding a way to achieve lookup, insertion and removal all in time O(log(n)).

We now turn to an idea, binary search trees, that, after some thought, will achieve that goal.


Binary search trees

Tree T is a binary search tree if the following is true for every node v in T.

If v has item k, then all nodes in the left subtree of v have items that are less than k, and all nodes in the right subtree of v have items that are greater than k. Graphically:


For example, the following is a binary search tree.

A binary search tree can have any shape, as long as it obeys the ordering requirement. The following is a binary search tree. (The left subtree of each node is an empty tree.)

A binary tree represents the set of all integers that occur in its nodes. An empty tree represents an empty set.