Optimal Binary Search Trees
Learn about the optimal binary search trees problem and its solution using backtracking.
We'll cover the following...
Introduction to optimal binary search trees
Our final example combines recursive backtracking with the divide-and-conquer strategy. Recall that the running time for a successful search in a binary search tree is proportional to the number of ancestors of the target node. As a result, the worst-case search time is proportional to the depth of the tree. Thus, to minimize the worst-case search time, the height of the tree should be as small as possible; by this metric, the ideal tree is perfectly balanced.
In many applications of binary search trees, however, it is more important to minimize the total cost of several searches rather than the worst-case cost of a single search. If is a more frequent search target than , we can save time by building a tree where the depth of is smaller than the depth of , even if that means increasing the overall depth of the tree. A perfectly balanced tree is not the best choice if some items are significantly more popular than others. In fact, a totally unbalanced tree with depth might actually be the best choice!
Problem statement
This situation suggests the following problem. Suppose we are given a sorted array of keys and an array of corresponding access frequencies . Our task is to build the binary search tree that minimizes the total search time, assuming that there will be exactly searches for each key .
Recurrence relation for optimal search tree
Before we think about how to solve this problem, we should first come up with a good recursive definition of the function we are trying to optimize! Suppose we are also given a binary search tree with nodes. Let be the nodes of , indexed in sorted order so that each node stores the corresponding key . Then ignoring constant factors, the total cost of performing all the binary searches is given by the following expression:
Now suppose is the root of ; by definition, is an ancestor of every node in . If , then all ancestors of ...