Optimal Binary Search Trees
A balanced binary search tree guarantees comparisons per lookup, whatever is looked up. But real lookups are not uniform. A spell-checker looks up "the" millions of times and "zymurgy" almost never; a compiler's symbol table is hit by a handful of hot identifiers. If you know the search frequencies in advance and the set of keys never changes, you can do better than balanced: put frequent keys near the root, even if the tree becomes lopsided. Finding the optimal binary search tree is an interval DP like matrix-chain multiplication, with one new twist in the cost.
The problem
Keys are searched times. A search for a key at depth (the root has depth 0) makes comparisons. The cost of a BST is the total number of comparisons:
Find a BST on these keys of minimum cost. The running example has seven keys:
| key | ant | bee | cat | dog | eel | fox | gnu |
|---|---|---|---|---|---|---|---|
| frequency | 13 | 4 | 11 | 1 | 15 | 3 | 2 |
Two obvious heuristics come to mind: the perfectly balanced tree (with dog at the root), and the greedy tree that puts the most frequent key at the root and recurses on both sides. The program computes the cost of both, and of the optimum, which the rest of the lesson explains.
keys = ["ant", "bee", "cat", "dog", "eel", "fox", "gnu"]
f = [13, 4, 11, 1, 15, 3, 2]
def cost_of(choose_root, i, j, depth=0):
"""total comparisons of the tree on keys i..j built by the given root rule"""
if i > j:
return 0
r = choose_root(i, j)
return f[r] * (depth + 1) + cost_of(choose_root, i, r - 1, depth + 1) + cost_of(choose_root, r + 1, j, depth + 1)
balanced = lambda i, j: (i + j) // 2
greedy = lambda i, j: max(range(i, j + 1), key=lambda t: f[t])
print("balanced tree :", cost_of(balanced, 0, 6))
print("greedy tree :", cost_of(greedy, 0, 6))
# brute force over every BST, to know the true optimum
from functools import cache
@cache
def best(i, j, depth):
if i > j:
return 0
return min(f[r] * (depth + 1) + best(i, r - 1, depth + 1) + best(r + 1, j, depth + 1) for r in range(i, j + 1))
print("optimal tree :", best(0, 6, 0))balanced tree : 138
greedy tree : 106
optimal tree : 99
The balanced tree is bad here because it puts the rarest key, dog, at the root, and greedy is better but not optimal. The search space is large: there are as many BSTs on keys as parenthesizations of matrices, the Catalan number , which is 429 for seven keys and about for thirty.
Optimal substructure and the recurrence
Any BST on has some root , . Its left subtree is a BST on and its right subtree on , because of the search-tree order. So subproblems are again intervals of keys, and cut and paste shows that in an optimal tree both subtrees must be optimal for their key ranges.
The twist is the depth. When a subtree hangs below a new root, every key in it moves one level deeper, which adds exactly its frequency to the cost. So with , the total cost of a tree with root is
The pleasant consequence is that does not depend on the choice of . With the minimum cost for keys :
Like matrix chains, fill the table by increasing interval length, and record the winning root in to rebuild the tree.
OPTIMAL-BST(f) // keys 1..n
1 e = new table [1..n+1, 0..n]; w = same shape; root = new table [1..n, 1..n]
2 for i = 1 to n + 1
3 e[i, i - 1] = 0; w[i, i - 1] = 0
4 for len = 1 to n
5 for i = 1 to n - len + 1
6 j = i + len - 1
7 w[i, j] = w[i, j - 1] + f[j]
8 e[i, j] = infinity
9 for r = i to j
10 t = e[i, r - 1] + e[r + 1, j] + w[i, j]
11 if t < e[i, j]
12 e[i, j] = t; root[i, j] = r
13 return e, rootkeys = ["ant", "bee", "cat", "dog", "eel", "fox", "gnu"]
f = [13, 4, 11, 1, 15, 3, 2]
def optimal_bst(f):
n = len(f)
e = [[0] * (n + 2) for _ in range(n + 2)] # e[i][i-1] = 0 is already in place
w = [[0] * (n + 2) for _ in range(n + 2)]
root = [[0] * (n + 1) for _ in range(n + 1)]
for length in range(1, n + 1):
for i in range(1, n - length + 2):
j = i + length - 1
w[i][j] = w[i][j - 1] + f[j - 1]
e[i][j] = float("inf")
for r in range(i, j + 1):
t = e[i][r - 1] + e[r + 1][j] + w[i][j]
if t < e[i][j]:
e[i][j], root[i][j] = t, r
return e, root
def show(root, i, j, depth=0, side="root"):
if i > j:
return
r = root[i][j]
print(" " * depth + f"{side}: {keys[r - 1]} ({f[r - 1]})")
show(root, i, r - 1, depth + 1, "L")
show(root, r + 1, j, depth + 1, "R")
e, root = optimal_bst(f)
n = len(f)
print("minimum cost e[1][7] =", e[1][n])
print("row i of e, columns i..7:")
for i in range(1, n + 1):
print(" " + " " * (i - 1) + "".join(f"{e[i][j]:5}" for j in range(i, n + 1)))
show(root, 1, n)minimum cost e[1][7] = 99
row i of e, columns i..7:
13 21 47 50 82 91 99
4 19 21 52 58 64
11 13 40 46 52
1 17 23 29
15 21 27
3 7
2
root: cat (11)
L: ant (13)
R: bee (4)
R: eel (15)
L: dog (1)
R: fox (3)
R: gnu (2)
The optimal tree matches the brute force. Notice its shape: the three frequent keys cat, ant and eel fill the top two levels, and dog, with a frequency of 1, is pushed down to a leaf, although it is the median key. The greedy rule would have put eel at the root, which leaves ant and cat (24 searches together) on one side, deeper than they need to be.
Running time, and Knuth's speed-up
There are intervals and each tries up to roots, so the algorithm takes time (the exact count of root trials is ) and space. Knuth observed in 1971 that the optimal roots are monotone: there is always an optimal choice with
so the loop over only needs to run between those two bounds. Summed along each diagonal, the ranges telescope to , and the whole algorithm drops to . The program checks on random inputs that the restricted loop finds the same costs, and counts the trials.
import random
def obst(f, knuth):
n = len(f)
pre = [0]
for x in f:
pre.append(pre[-1] + x)
e = [[0] * (n + 2) for _ in range(n + 2)]
root = [[0] * (n + 2) for _ in range(n + 2)]
trials = 0
for i in range(1, n + 1):
e[i][i], root[i][i] = f[i - 1], i
trials += 1
for length in range(2, n + 1):
for i in range(1, n - length + 2):
j = i + length - 1
lo, hi = (root[i][j - 1], root[i + 1][j]) if knuth else (i, j)
best = None
for r in range(lo, hi + 1):
trials += 1
t = e[i][r - 1] + e[r + 1][j]
if best is None or t < best:
best, root[i][j] = t, r
e[i][j] = best + pre[j] - pre[i - 1]
return e[1][n], trials
rng = random.Random(11)
for n in [10, 40, 120]:
f = [rng.randint(0, 1000) for _ in range(n)]
plain, knuth = obst(f, False), obst(f, True)
print(f"n = {n:3}: cost {plain[0]:7} vs {knuth[0]:7}, trials {plain[1]:6} (n^3 algorithm) vs {knuth[1]:5} (Knuth)")n = 10: cost 18960 vs 18960, trials 220 (n^3 algorithm) vs 98 (Knuth)
n = 40: cost 76027 vs 76027, trials 11480 (n^3 algorithm) vs 1537 (Knuth)
n = 120: cost 288583 vs 288583, trials 295240 (n^3 algorithm) vs 14597 (Knuth)
The costs agree, and the number of trials grows like for the plain loop but only like for Knuth's version. The same monotonicity trick (known more generally as the Knuth-Yao speed-up) applies to other interval DPs whose cost satisfies the quadrangle inequality, but not to matrix chains.
Unsuccessful searches
The textbook form of the problem also accounts for searches that fail: between consecutive keys (and before the first and after the last) lie gaps, and a search for a value in gap ends at a missing child. Give those gaps frequencies and count a failed search as ending one level below the last key it compared with. The same derivation goes through with and base case ; only the bookkeeping changes. The practice problem Optimal Binary Search Tree uses the version of this lesson, with successful searches only.
In C++
#include <climits>
#include <cstdio>
#include <string>
#include <vector>
std::vector<std::string> keys = {"ant", "bee", "cat", "dog", "eel", "fox", "gnu"};
std::vector<std::vector<int>> root;
void show(int i, int j, int depth) {
if (i > j) return;
int r = root[i][j];
std::printf("%*s%s\n", 2 * depth, "", keys[r - 1].c_str());
show(i, r - 1, depth + 1);
show(r + 1, j, depth + 1);
}
int main() {
std::vector<int> f = {13, 4, 11, 1, 15, 3, 2};
int n = static_cast<int>(f.size());
std::vector<std::vector<int>> e(n + 2, std::vector<int>(n + 2, 0)), w = e;
root.assign(n + 2, std::vector<int>(n + 2, 0));
for (int len = 1; len <= n; ++len)
for (int i = 1; i + len - 1 <= n; ++i) {
int j = i + len - 1;
w[i][j] = w[i][j - 1] + f[j - 1];
e[i][j] = INT_MAX;
for (int r = i; r <= j; ++r) {
int t = e[i][r - 1] + e[r + 1][j] + w[i][j];
if (t < e[i][j]) { e[i][j] = t; root[i][j] = r; }
}
}
std::printf("minimum cost %d; tree in preorder, indented by depth:\n", e[1][n]);
show(1, n, 0);
}minimum cost 99; tree in preorder, indented by depth:
cat
ant
bee
eel
dog
fox
gnu
Test yourself
Why is added in the recurrence for , whatever the root?
- It is the cost of the root alone
- Hanging the two subtrees under the root makes every key in one level deeper, except the root, whose single comparison is also counted: in total
- It is a penalty for unbalanced trees
- It is the number of keys in the range
Keys with frequencies , . What is the minimum cost?
- 6
- 7
- 11
- 12
What does Knuth's monotonicity observation reduce the running time of the optimal-BST DP to?
- It does not change the running time
Is the greedy rule 'put the most frequent key at the root' optimal?
- Yes, always
- No: in this lesson's example it costs more than the optimum
- Only if all frequencies are equal
- Yes, if the tree is balanced afterwards