Optimal Binary Search Tree
When some keys are searched far more often than others, a balanced tree is not the cheapest. An optimal BST places keys so the expected number of comparisons is as small as possible.
Minimising the Expected Search Cost
- Keys – n distinct keys in sorted order, k₁ < k₂ < … < kₙ.
- Successful-search weights – pᵢ, how often kᵢ is searched for.
- Unsuccessful-search weights – qᵢ, how often a search falls between kᵢ and kᵢ₊₁ (optional; many problems set them to 0).
- Goal – the BST with the minimum Σ pᵢ·depth(kᵢ), plus Σ qᵢ·depth(dᵢ) when dummy keys are counted.
An optimal binary search tree (OBST) is a binary search tree over sorted keys k₁ < k₂ < … < kₙ that minimises the expected search cost, given how often each key is searched for.
Finding a key at depth d takes d comparisons. If key kᵢ is searched with frequency (or probability) pᵢ, the cost of a tree is Σ pᵢ × depth(kᵢ). The diagram at the top shows why a balanced tree can lose: C is searched most, and the balanced shape puts it at depth 2. Moving C to the root drops the cost from 21 to 17.
Where the key set is fixed and search frequencies are known in advance, this is the tree to build: a compiler's reserved-word table, a spelling dictionary, a static routing table.
- Balanced minimises the worst case, not the average – the two goals agree only when every key is searched equally often
- Equal frequencies give a balanced tree – with all pᵢ the same, the cheapest shape is the one with the smallest total depth
- The answer is still a valid BST – an in-order walk gives the keys in sorted order
Why Greedy Fails and Dynamic Programming Works
The tempting shortcut is to put the most frequent key at the root and repeat on each side. It fails because the root also pushes every other key one level down, so a moderately popular key in the middle can beat a very popular key at the edge.
Example: keys A, B, C with frequencies 3, 2, 3. Greedy puts A (or C) at the root, then C, then B beneath it: 3·1 + 3·2 + 2·3 = 15. Rooting at the least frequent key, B, gives 2·1 + 3·2 + 3·2 = 14. Greedy is not optimal.
The problem has optimal substructure: if key kᵣ is the root of an optimal tree for keys i..j, then its left subtree must be optimal for i..r−1 and its right subtree optimal for r+1..j. Otherwise swapping in a cheaper subtree would lower the total. And the same ranges i..j are needed by many different parents, so they overlap. Those two properties are what make dynamic programming the right tool.
- Ranges, not subsets – a subtree always holds a contiguous run of the sorted keys, so there are only n(n+1)/2 states
- Short ranges first – the same fill order as matrix-chain multiplication
The Recurrence and the Algorithm
- State – cost(i, j) is the minimum cost of a BST built from keys i..j. Empty ranges cost 0.
- Recurrence – cost(i, j) = min over r in i..j of [cost(i, r−1) + cost(r+1, j)] + w(i, j).
- Weight – w(i, j) = pᵢ + … + pⱼ (+ qᵢ₋₁ + … + qⱼ with dummy keys). Every key in the range sits one level deeper under the root, so the whole weight is paid once more.
- Order – fill by range length 1, 2, …, n, so both sub-ranges are always ready.
- Root table – store the minimising r as root(i, j) to rebuild the tree afterwards.
The weight term is the part students most often forget. The left and right subtree costs were computed as if their roots sat at depth 1. Hanging them under kᵣ adds one comparison to every search in the range, which is exactly w(i, j), and kᵣ's own search costs pᵣ, which is also inside w(i, j).
Prefix sums make every w(i, j) an O(1) lookup, so each cell costs O(j − i + 1) for the candidate roots. The tracer fills the full table for four keys and then reads the tree back out of the root table.
- A single key – cost(i, i) = pᵢ with root i; the only candidate has two empty sides
- A key nobody searches (pᵢ = 0) still needs a place; it sinks towards the leaves
- Ties between roots – both give the same cost; pick one rule (say the smallest r) so the root table is reproducible
Terms, operations, and practical uses
Core vocabulary
- Expected search costΣ pᵢ·depth(kᵢ), plus Σ qᵢ·depth(dᵢ) with dummy keys.
- Dummy key dᵢA leaf standing for all failed searches between kᵢ and kᵢ₊₁.
- w(i, j)Total weight of the range; added once per level of nesting.
- root(i, j)The key chosen as root for keys i..j; used to rebuild the tree.
Exam checklist
- State the recurrenceIncluding the w(i, j) term and the base case.
- Fill orderBy increasing range length, one diagonal at a time.
- Show the tablew, c and root for every range.
- Draw the treeFrom root(0, n) downwards, with dummy leaves if q is given.
Related lessons
- Binary search treesThe ordering property every OBST keeps.
- Dynamic programmingOptimal substructure and overlapping subproblems.
- Two-dimensional DPTables indexed by a pair of positions.
- AVL treesBalance for the worst case instead of the average.
Code in Python, C++ and Java
def optimal_bst(keys, freq):
n = len(keys)
# cost[i][j] = cheapest search cost for keys i..j; empty ranges cost 0.
cost = [[0] * (n + 1) for _ in range(n + 2)]
root = [[0] * (n + 1) for _ in range(n + 2)]
prefix = [0]
for f in freq:
prefix.append(prefix[-1] + f)
for length in range(1, n + 1):
for i in range(1, n - length + 2):
j = i + length - 1
best, best_root = float("inf"), i
for r in range(i, j + 1):
c = cost[i][r - 1] + cost[r + 1][j]
if c < best:
best, best_root = c, r
# Every key in i..j sits one level deeper under the chosen root.
cost[i][j] = best + prefix[j] - prefix[i - 1]
root[i][j] = best_root
return cost[1][n], root
def build(keys, root, i, j):
if i > j:
return "-"
r = root[i][j]
left, right = build(keys, root, i, r - 1), build(keys, root, r + 1, j)
if left == right == "-":
return keys[r - 1]
return f"{keys[r - 1]}({left}, {right})"
keys = ["A", "B", "C", "D"]
freq = [1, 2, 4, 3]
total, root = optimal_bst(keys, freq)
print("minimum cost:", total)
print("root:", keys[root[1][len(keys)] - 1])
print("tree:", build(keys, root, 1, len(keys)))#include <climits>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> keys = {"A", "B", "C", "D"};
vector<vector<int>> root;
string build(int i, int j) {
if (i > j) return "-";
int r = root[i][j];
string left = build(i, r - 1), right = build(r + 1, j);
if (left == "-" && right == "-") return keys[r - 1];
return keys[r - 1] + "(" + left + ", " + right + ")";
}
int main() {
vector<int> freq = {1, 2, 4, 3};
int n = keys.size();
// cost[i][j] = cheapest search cost for keys i..j; empty ranges cost 0.
vector<vector<int>> cost(n + 2, vector<int>(n + 1, 0));
root.assign(n + 2, vector<int>(n + 1, 0));
vector<int> prefix(n + 1, 0);
for (int k = 1; k <= n; k++) prefix[k] = prefix[k - 1] + freq[k - 1];
for (int length = 1; length <= n; length++) {
for (int i = 1; i + length - 1 <= n; i++) {
int j = i + length - 1, best = INT_MAX, bestRoot = i;
for (int r = i; r <= j; r++) {
int c = cost[i][r - 1] + cost[r + 1][j];
if (c < best) {
best = c;
bestRoot = r;
}
}
// Every key in i..j sits one level deeper under the chosen root.
cost[i][j] = best + prefix[j] - prefix[i - 1];
root[i][j] = bestRoot;
}
}
cout << "minimum cost: " << cost[1][n] << "\n";
cout << "root: " << keys[root[1][n] - 1] << "\n";
cout << "tree: " << build(1, n) << "\n";
}public class Main {
static String[] keys = {"A", "B", "C", "D"};
static int[][] root;
static String build(int i, int j) {
if (i > j) return "-";
int r = root[i][j];
String left = build(i, r - 1), right = build(r + 1, j);
if (left.equals("-") && right.equals("-")) return keys[r - 1];
return keys[r - 1] + "(" + left + ", " + right + ")";
}
public static void main(String[] args) {
int[] freq = {1, 2, 4, 3};
int n = keys.length;
// cost[i][j] = cheapest search cost for keys i..j; empty ranges cost 0.
int[][] cost = new int[n + 2][n + 1];
root = new int[n + 2][n + 1];
int[] prefix = new int[n + 1];
for (int k = 1; k <= n; k++) prefix[k] = prefix[k - 1] + freq[k - 1];
for (int length = 1; length <= n; length++) {
for (int i = 1; i + length - 1 <= n; i++) {
int j = i + length - 1, best = Integer.MAX_VALUE, bestRoot = i;
for (int r = i; r <= j; r++) {
int c = cost[i][r - 1] + cost[r + 1][j];
if (c < best) {
best = c;
bestRoot = r;
}
}
// Every key in i..j sits one level deeper under the chosen root.
cost[i][j] = best + prefix[j] - prefix[i - 1];
root[i][j] = bestRoot;
}
}
System.out.println("minimum cost: " + cost[1][n]);
System.out.println("root: " + keys[root[1][n] - 1]);
System.out.println("tree: " + build(1, n));
}
}Step through it
Running on keys A, B, C, D with frequencies 1, 2, 4, 3
Worked Example With Dummy Keys
This is the textbook version with unsuccessful searches, as set in most university exams. The ranges are written as (i, j] so the dummy leaves fit neatly.
- Keys – k₁ < k₂ < k₃ with success weights p = (3, 3, 1).
- Dummy keys – d₀ … d₃ with failure weights q = (2, 3, 1, 1), where dᵢ stands for searches falling between kᵢ and kᵢ₊₁.
- Notation – w(i, j) = q_i + Σ(pₖ + qₖ) for k = i+1..j, and c(i, i) = 0, w(i, i) = qᵢ.
- Recurrence – c(i, j) = w(i, j) + min over i < r ≤ j of [c(i, r−1) + c(r, j)].
Length 1. w(0,1) = 2 + 3 + 3 = 8, so c(0,1) = 8 with root k₁. Likewise c(1,2) = w(1,2) = 7 with root k₂, and c(2,3) = w(2,3) = 3 with root k₃.
Length 2. w(0,2) = 12. Root k₁: c(0,0) + c(1,2) = 0 + 7 = 7. Root k₂: c(0,1) + c(2,2) = 8 + 0 = 8. The minimum is 7, so c(0,2) = 19 with root k₁. For (1,3], w = 9; root k₂ gives 0 + 3 = 3 and root k₃ gives 7 + 0 = 7, so c(1,3) = 12 with root k₂.
Length 3. w(0,3) = 14. Root k₁: 0 + 12 = 12. Root k₂: 8 + 3 = 11. Root k₃: 19 + 0 = 19. The minimum is 11, so c(0,3) = 25 with root k₂. Rebuilding: k₂ is the root, root(0,1) = k₁ on the left, root(2,3) = k₃ on the right.
| Range | w(i, j) | c(i, j) | root |
|---|---|---|---|
| (0, 1] | 8 | 8 | k₁ |
| (1, 2] | 7 | 7 | k₂ |
| (2, 3] | 3 | 3 | k₃ |
| (0, 2] | 12 | 19 | k₁ |
| (1, 3] | 9 | 12 | k₂ |
| (0, 3] | 14 | 25 | k₂ |
- Dummy leaves count one level less than they are drawn – d₀ hangs at level 3 but adds 2·q₀, because the failed search stops after two comparisons
- Check by depths – keys: 3·2 + 3·1 + 1·2 = 11; dummies: (2 + 3 + 1 + 1)·2 = 14; total 25, matching c(0, 3)
- Without dummy keys (all q = 0) the same tables work, with w(i, i) = 0
Time and Space Complexity
There are about n²/2 ranges, and each tries up to n roots, so the direct algorithm runs in O(n³) time and O(n²) space for the cost, weight and root tables.
Knuth's optimisation (1971) cuts this to O(n²). It proves that the optimal root never moves left as a range grows: root(i, j−1) ≤ root(i, j) ≤ root(i+1, j). Restricting the loop over r to that window makes the total work along each diagonal O(n), so O(n²) overall.
Rebuilding the tree from the root table is O(n): one lookup per key.
| Algorithm | Time | Space |
|---|---|---|
| Try every tree | Catalan number, grows like 4ⁿ / n^1.5 | O(n) |
| DP over ranges | O(n³) | O(n²) |
| DP + Knuth's root bound | O(n²) | O(n²) |
| Reconstruction | O(n) | O(n) recursion |
- Brute force is hopeless early – 4 keys already allow 14 tree shapes, 10 keys allow 16,796
- Knuth's window is not special to trees – it carries over to other interval DPs whose cost satisfies the quadrangle inequality (Yao, 1980)
Where Optimal BSTs Are Used, and Their Limits
OBSTs fit static lookups with known, skewed frequencies: a compiler's keyword table, a word list in a spell-checker, a lookup in a code generator. The same range recurrence also solves problems with the same shape, such as matrix chain multiplication and optimal polygon triangulation.
The limits are real. If keys are inserted or deleted, the tree must be rebuilt. If frequencies are unknown or drift, a splay tree adapts on the fly and is provably within a constant factor of the optimal static tree over a long run. And for pure lookups, a hash table gives O(1) expected time without any ordering at all.
- Any insert or delete means rerunning the whole table
- Frequencies measured on old traffic may not match tomorrow's searches
- A hash table loses range queries and sorted order; an OBST keeps both