How an optimal BST weights search cost

Short answer: An optimal binary search tree puts keys in search-tree order and chooses the shape that minimizes the expected search cost. Key i is requested with probability p[i], and the gap between keys is requested with probability q[i]. The cost of a subtree is the sum of its probabilities, plus the optimal costs of its left and right subtrees, because every search pays one comparison at the root and then continues. The interval DP is O(n³) in the basic form, and Knuth’s optimization reduces it to O(n²).


What the problem actually asks

A balanced tree minimizes the worst-case height. A search tree whose keys have very different probabilities should put the frequent keys closer to the root, while still obeying the in-order key order. The legal roots of an interval of keys are the keys inside it. Choosing key r as the root splits the interval into a left interval and a right interval, both of which are independent optimal-BST subproblems.

Every search that lands in the subtree pays for the root comparison. That extra charge equals the total probability mass of the subtree, and it is added on top of the children’s already-optimal costs. Forgetting the mass produces a tree that minimizes the wrong quantity.


What the algorithm guarantees

The DP returns the minimum expected search cost and, with stored roots, one tree that attains it. The basic triple loop is Θ(n³). Knuth’s optimization uses the fact that the optimal root moves monotonically as the interval slides, and it cuts the search for the root down to O(n²) total. Extra memory is Θ(n²). The probabilities of keys and gaps must be nonnegative and sum to 1 if the result is to be read as an expectation. The same recurrence with unnormalized weights minimizes a weighted path length.

The tree is a binary search tree, so the in-order sequence is fixed. The DP does not reorder keys. It only chooses parents.


The working steps

  1. Index keys 1..n in sorted order. Let q[0], …, q[n] be the probabilities of the gaps, including the searches that fall outside the key set.
  2. Precompute the sum of probabilities of every interval, so the mass of a subtree is a subtraction.
  3. The cost of an empty gap is 0, or the gap probability alone, according to the chosen charging convention. Pick one convention and use it in the mass term.
  4. For increasing interval length, try each legal root and set the interval’s cost to its probability mass plus the optimal left cost plus the optimal right cost. Keep the minimizing root.
  5. With Knuth’s optimization, restrict the root search for interval (i, j) to the range between the optimal root of (i, j−1) and the optimal root of (i+1, j).

The cubic or quadratic bound is the number of intervals and candidate roots, not the cost of later searches. A treap or a splay tree adapts to an unknown distribution online. This DP needs the probabilities in advance and builds a static tree. A Huffman tree ignores the search-tree order and is optimal for a different constraint, the prefix code.


Approaches that look simpler and fail

Approach Why it fails when the subtree’s own probability mass is omitted
Add only the left and right children’s costs Every search pays for the root. The missing term is the probability mass of the whole subtree, and without it a deep frequent key looks cheaper than it is.
Reorder keys to put the highest probability at the root The result may not be a binary search tree. The in-order sequence is fixed by the key order.
Use Huffman merging on the probabilities Huffman optimizes a prefix code and may place a key in an order the search tree forbids.
Run the cubic loop and cite Knuth’s O(n²) bound The quadratic bound needs the monotonic root restriction. The unrestricted triple loop is cubic.

A prefix code with no key order is Huffman. An online adaptive search tree is a splay tree. The optimal BST is the static interval DP for known search probabilities.


A working example

This Python fragment builds an optimal BST by interval length. The cost of a root adds the probability mass of the whole interval. Keys have probabilities 0.2, 0.5, 0.3. Probabilities are stored as percents 20, 50, and 30. It prints the minimum expected cost 150, which is 1.50 in the original units.

p = [0, 20, 50, 30]  # tenths of a percent, dummy at index 0
n = 3
w = [[0] * (n + 2) for _ in range(n + 2)]
e = [[0] * (n + 2) for _ in range(n + 2)]
for i in range(1, n + 2):
    w[i][i - 1] = 0
    e[i][i - 1] = 0
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] + p[j]
        e[i][j] = min(e[i][r - 1] + e[r + 1][j] for r in range(i, j + 1)) + w[i][j]
assert e[1][n] == 150
print(e[1][n])

Where it is used

An optimal binary search tree is a static dictionary whose lookup frequencies are known, such as a compiler keyword table built once. The dynamic program places frequent keys nearer the root. A red-black tree is the structure when keys arrive online.


When you can drop this algorithm

Drop the DP when the probabilities are unknown. A balanced tree or a splay tree is the honest alternative. Keep it when the request probabilities are known and the tree must stay in key order.


Why this stays published

We publish this so a search for the optimal binary search tree returns the interval DP, the probability-mass charge, and Knuth’s quadratic speedup. An optimal BST is an interval DP that adds each subtree’s probability mass to the cost of its children, in O(n³) time, or O(n²) with Knuth’s root restriction.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *