Sub topic 14
Counting Binary Search Trees with Catalan Numbers
This chapter assumes that you know recursion, binary search tree (BST) ordering, arrays, and Big-O notation. We count structurally different BSTs that contain the same set of distinct keys.
Why root choices create a recurrence
Suppose a BST contains the sorted keys:
1, 2, 3, ..., nIf key r is the root, then:
- The
r - 1smaller keys must form the left subtree. - The
n - rlarger keys must form the right subtree. - Every possible left subtree can combine with every possible right subtree.
Let C_n be the number of distinct BST shapes containing n distinct keys. For a fixed root position r, the number of trees is:
\[ C{r-1}C{n-r} \]
The root can be any of the n keys, so:
\[ Cn=\sum{r=1}^{n} C{r-1}C{n-r} \]
With an empty tree counted as one possibility, C_0 = 1.
Changing the actual key values does not change the count. For example, the keys {10, 20, 30} have the same number of BST shapes as {1, 2, 3} because only their relative order matters.
Catalan numbers
The recurrence above produces the Catalan numbers:
\[ C_n=\frac{1}{n+1}\binom{2n}{n} \]
The binomial coefficient is:
\[ \binom{2n}{n}=\frac{(2n)!}{n!n!} \]
The first values are:
| Number of keys `n` | Number of distinct BSTs `C_n` |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
| 3 | 5 |
| 4 | 14 |
| 5 | 42 |
| 6 | 132 |
For n = 3, the five trees include three choices of root:
- Root
1: one left shape and one right shape. - Root
2: one left shape and one right shape. - Root
3: one left shape and one right shape.
For three keys, the recurrence gives:
\[ C3=C0C2+C1C1+C2C_0 =1\cdot2+1\cdot1+2\cdot1=5 \]
Computing the count with dynamic programming
A direct recursive implementation repeats the same subproblems. Dynamic programming stores earlier Catalan values and reuses them.
def count_bsts(n):
catalan = [0] * (n + 1)
catalan[0] = 1
for nodes in range(1, n + 1):
for left_nodes in range(nodes):
right_nodes = nodes - 1 - left_nodes
catalan[nodes] += (
catalan[left_nodes] * catalan[right_nodes]
)
return catalan[n]
for n in range(7):
print(n, count_bsts(n))The algorithm takes \(O(n^2)\) time because it evaluates n entries, and each entry considers up to n root splits. It uses \(O(n)\) extra space.
Common errors
- Counting only possible root keys and forgetting that each root can have many subtree shapes.
- Using
C_n = C_{n-1} + C_{n-2}, which is not the BST-shape recurrence. - Treating an empty subtree as zero possibilities. It must count as one possibility, because it is one valid choice.
- Confusing tree shapes with insertion orders. Several insertion orders can produce the same BST.
Exercise
How many distinct BSTs can be formed from four distinct keys? Show the recurrence calculation.
Show answer
There are C4 = C0C3 + C1C2 + C2C1 + C3C0 = 1·5 + 1·2 + 2·1 + 5·1 = 14 distinct BSTs.