TExcelTAD

Optimal Binary Search Trees

A balanced binary search tree guarantees O(lg⁡n)O(\lg n) 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 k1<k2<⋯<knk_1 < k_2 < \cdots < k_n are searched f1,f2,…,fnf_1, f_2, \ldots, f_n times. A search for a key at depth dd (the root has depth 0) makes d+1d + 1 comparisons. The cost of a BST TT is the total number of comparisons:

cost(T)=∑i=1nfi⋅(depth⁡T(ki)+1).\text{cost}(T) = \sum_{i=1}^{n} f_i \cdot \bigl(\operatorname{depth}_T(k_i) + 1\bigr).

Find a BST on these keys of minimum cost. The running example has seven keys:

key ant bee cat dog eel fox gnu
frequency fif_i 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.

python · try it yourself
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 nn keys as parenthesizations of n+1n + 1 matrices, the Catalan number 1n+1(2nn)\frac{1}{n+1}\binom{2n}{n}, which is 429 for seven keys and about 3.8×10153.8 \times 10^{15} for thirty.

Optimal substructure and the recurrence

Any BST on ki,…,kjk_i, \ldots, k_j has some root krk_r, i≤r≤ji \le r \le j. Its left subtree is a BST on ki,…,kr−1k_i, \ldots, k_{r-1} and its right subtree on kr+1,…,kjk_{r+1}, \ldots, k_j, 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 w(i,j)=fi+fi+1+⋯+fjw(i, j) = f_i + f_{i+1} + \cdots + f_j, the total cost of a tree with root krk_r is

cost=cost(L)+w(i,r−1)⏟left side, one level deeper+fr⏟root+cost(R)+w(r+1,j)⏟right side, one level deeper=cost(L)+cost(R)+w(i,j).\text{cost} = \underbrace{\text{cost}(L) + w(i, r - 1)}_{\text{left side, one level deeper}} + \underbrace{f_r}_{\text{root}} + \underbrace{\text{cost}(R) + w(r + 1, j)}_{\text{right side, one level deeper}} = \text{cost}(L) + \text{cost}(R) + w(i, j).

The pleasant consequence is that w(i,j)w(i, j) does not depend on the choice of rr. With e[i,j]e[i, j] the minimum cost for keys i..ji..j:

e[i,j]={0if j=i−1 (no keys),w(i,j)+min⁡i≤r≤j(e[i,r−1]+e[r+1,j])if i≤j.e[i, j] = \begin{cases} 0 & \text{if } j = i - 1 \text{ (no keys)}, \\ w(i, j) + \min\limits_{i \le r \le j} \bigl( e[i, r-1] + e[r+1, j] \bigr) & \text{if } i \le j. \end{cases}

Like matrix chains, fill the table by increasing interval length, and record the winning root in root[i,j]\mathit{root}[i, j] to rebuild the tree.

text
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, root
python · try it yourself
keys = ["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 Θ(n2)\Theta(n^2) intervals and each tries up to nn roots, so the algorithm takes Θ(n3)\Theta(n^3) time (the exact count of root trials is (n+23)\binom{n+2}{3}) and Θ(n2)\Theta(n^2) space. Knuth observed in 1971 that the optimal roots are monotone: there is always an optimal choice with

root[i,j−1]≤root[i,j]≤root[i+1,j],\mathit{root}[i, j - 1] \le \mathit{root}[i, j] \le \mathit{root}[i + 1, j],

so the loop over rr only needs to run between those two bounds. Summed along each diagonal, the ranges telescope to O(n)O(n), and the whole algorithm drops to Θ(n2)\Theta(n^2). The program checks on random inputs that the restricted loop finds the same costs, and counts the trials.

python · try it yourself
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 n3/6n^3/6 for the plain loop but only like n2n^2 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 n+1n + 1 gaps, and a search for a value in gap gg ends at a missing child. Give those gaps frequencies q0,…,qnq_0, \ldots, q_n and count a failed search as ending one level below the last key it compared with. The same derivation goes through with w(i,j)=fi+⋯+fj+qi−1+⋯+qjw(i, j) = f_i + \cdots + f_j + q_{i-1} + \cdots + q_j and base case e[i,i−1]=qi−1e[i, i-1] = q_{i-1}; only the bookkeeping changes. The practice problem Optimal Binary Search Tree uses the version of this lesson, with successful searches only.

In C++

cpp · try it yourself
#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 w(i,j)w(i, j) added in the recurrence for e[i,j]e[i, j], whatever the root?

  1. It is the cost of the root alone
  2. Hanging the two subtrees under the root makes every key in i..ji..j one level deeper, except the root, whose single comparison is also counted: in total w(i,j)w(i, j)
  3. It is a penalty for unbalanced trees
  4. It is the number of keys in the range

Keys k1<k2k_1 < k_2 with frequencies f1=5f_1 = 5, f2=1f_2 = 1. What is the minimum cost?

  1. 6
  2. 7
  3. 11
  4. 12

What does Knuth's monotonicity observation reduce the running time of the optimal-BST DP to?

  1. Θ(nlg⁡n)\Theta(n \lg n)
  2. Θ(n2)\Theta(n^2)
  3. Θ(n2lg⁡n)\Theta(n^2 \lg n)
  4. It does not change the running time

Is the greedy rule 'put the most frequent key at the root' optimal?

  1. Yes, always
  2. No: in this lesson's example it costs more than the optimum
  3. Only if all frequencies are equal
  4. Yes, if the tree is balanced afterwards