Sub topic 14
Counting BSTs with Catalan numbers
This chapter assumes you know the binary search tree (BST) property, how insertion works, and what a tree's shape is. It also assumes you can read a simple recurrence and use binomial coefficients. The goal is to answer "how many distinct BSTs exist on n keys?" and its common variants, which GATE tests as short numerical questions.
What is being counted
Two BSTs are distinct if their shapes differ once the keys are fixed. With distinct keys, a given set of n keys has exactly one BST for each valid shape, because the BST property fixes where every key goes. So counting BSTs on n distinct keys is the same as counting binary tree shapes with n nodes.
Insertion order is a different thing. Different insertion orders can build the same tree. Inserting 2, 1, 3 and inserting 2, 3, 1 both give a tree with root 2 and children 1 and 3. Counting trees and counting permutations give different answers.
For n = 3 there are 3! = 6 insertion orders but only 5 distinct BSTs.
Deriving the recurrence
Let T(n) be the number of BSTs on n distinct keys. Sort the keys as 1, 2, ..., n and choose the root key k.
- Keys 1 to k−1 are smaller than k, so they must all lie in the left subtree. There are k−1 of them.
- Keys k+1 to n are larger, so they must all lie in the right subtree. There are n−k of them.
- The left and right subtrees are chosen independently, so the counts multiply.
This gives T(n) = sum over k = 1..n of T(k−1) · T(n−k), with T(0) = 1. The empty tree counts as one tree, which is why T(0) = 1 and not 0. If T(0) were 0, every product with an empty side would vanish.
It is convenient to write the sum with i = k−1 as the size of the left subtree:
T(n) = sum for i = 0..n−1 of T(i) · T(n−1−i)
This is the Catalan recurrence, so T(n) = C_n, the nth Catalan number.
Worked example: n = 3
| Root | Left keys | Right keys | Count |
|---|---|---|---|
| 1 | 0 | 2 | C0 · C2 = 1 · 2 = 2 |
| 2 | 1 | 1 | C1 · C1 = 1 · 1 = 1 |
| 3 | 2 | 0 | C2 · C0 = 2 · 1 = 2 |
The total is 2 + 1 + 2 = 5.
The closed form
The recurrence has a closed form:
C_n = (1 / (n+1)) · binomial(2n, n) = (2n)! / ((n+1)! · n!)
The first values are worth memorising for GATE.
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| C_n | 1 | 1 | 2 | 5 | 14 | 42 | 132 | 429 | 1430 | 4862 | 16796 |
For larger n, use the ratio form, which is easier by hand:
C{n+1} = Cn · 2(2n+1) / (n+2)
Check: C5 = C4 · 2·9 / 6 = 14 · 3 = 42.
Catalan numbers grow roughly like 4^n / (n^1.5 · sqrt(pi)). That is exponential, so the number of BSTs explodes quickly. For example, C_20 = 6564120420.
Checking by brute force
The next program inserts every permutation of 1..n into an empty BST. It collects the distinct tree shapes in a set and compares the count with both Catalan formulas. Trees are stored as nested tuples so they are hashable.
from itertools import permutations
from math import comb
def insert(tree, key):
if tree is None:
return (key, None, None)
k, left, right = tree
if key < k:
return (k, insert(left, key), right)
return (k, left, insert(right, key))
def build_tree(order):
tree = None
for key in order:
tree = insert(tree, key)
return tree
def catalan_dp(n):
c = [0] * (n + 1)
c[0] = 1
for m in range(1, n + 1):
c[m] = sum(c[i] * c[m - 1 - i] for i in range(m))
return c[n]
def catalan_closed(n):
return comb(2 * n, n) // (n + 1)
for n in range(1, 8):
shapes = {build_tree(p) for p in permutations(range(1, n + 1))}
print(n, len(list(permutations(range(1, n + 1)))), len(shapes),
catalan_dp(n), catalan_closed(n))The output columns are n, the number of permutations, the number of distinct BSTs, and the two Catalan values:
1 1 1 1 1
2 2 2 2 2
3 6 5 5 5
4 24 14 14 14
5 120 42 42 42
6 720 132 132 132
7 5040 429 429 429The permutation count n! quickly outgrows C_n, so many insertion orders produce the same tree.
Variants that GATE asks
Fixed root
The number of BSTs on keys 1..n whose root is k is C{k−1} · C{n−k}. For 6 keys with root 4, the left side has 3 keys and the right side has 2, so the count is C3 · C2 = 5 · 2 = 10.
Unlabelled and labelled binary trees
The same number C_n counts several different objects, so read the question carefully.
| Object | Count |
|---|---|
| BSTs on n distinct keys | C_n |
| Binary tree shapes with n unlabelled nodes | C_n |
| Binary trees with n distinct labels, any arrangement | C_n · n! |
| Insertion orders (permutations) of n keys | n! |
| Full binary trees with n internal nodes (n+1 leaves) | C_n |
| Binary trees of maximum height n−1 (BSTs on n keys) | 2^(n−1) |
The labelled count C_n · n! works because each shape can receive the n labels in n! ways, and different (shape, labelling) pairs give different trees. For 3 nodes this gives 5 · 6 = 30.
For the last row, a tree of height n−1 has exactly one node per level. Each non-root node is either the left or right child of the previous one, which gives 2 choices at each of the n−1 steps. For n = 3 that is 4 trees: the chain 1-2-3, the chain 3-2-1, and the two zig-zag shapes.
Same traversal, many trees
If you are told only the preorder sequence of n nodes and nothing else about their keys, the number of binary tree shapes consistent with it is C_n. That is why a single traversal does not determine a general binary tree. For a BST with known keys, the preorder sequence does determine the tree, because the BST property supplies the missing information.
Other Catalan objects
The same sequence counts several other structures. Each one has the same "pick a split point, multiply the two sides" recurrence.
- Valid strings of n pairs of balanced parentheses.
- Triangulations of a convex polygon with n+2 sides.
- Stack-sortable permutations of n items, which are the output orders of a stack that receives items 1..n in order.
Common errors
- Using n! instead of C_n. The permutation count is larger because several orders give the same tree. For n = 3 the answer is 5, not 6.
- Setting C0 = 0. The empty subtree is one valid choice. Without C0 = 1 the root-at-minimum case contributes nothing and the recurrence collapses.
- Off-by-one in the index. A tree with n nodes has count Cn. A polygon with n+2 sides has Cn triangulations. Check which quantity the question gives you.
- Mixing up trees and insertion orders. If a question asks how many insertion sequences produce one particular tree, the answer is not C_n.
For example, for the tree with root 2 and children 1 and 3, the root must go first and the two children can follow in either order. That gives 2 sequences. In general the answer comes from counting valid interleavings of the subtree sequences.
Why shape counts do not tell you typical height
A uniformly random shape and a tree built from a random insertion order are not the same distribution. Among the 3! = 6 orders, the balanced tree appears twice, while each chain appears once. Balanced shapes are far more likely under random insertion.
This is why the average height of a BST built by random insertion is O(log n). By contrast, a uniformly random binary tree shape has expected height on the order of sqrt(n). The count C_n alone does not give the average cost of BST operations. The distribution over trees matters, and that connects back to the cost analysis in terms of height.
Exercise
How many distinct BSTs can be built from the keys 1, 2, 3, 4, 5, 6 so that 4 is the root?
Show answer
The left subtree holds keys 1, 2, 3 (3 keys) and the right subtree holds keys 5, 6 (2 keys). The count is C3 · C2 = 5 · 2 = 10.
Exercise
How many distinct binary trees exist with 3 nodes carrying the distinct labels A, B, C, where trees that differ in shape or in labelling count as different?
Show answer
There are C_3 = 5 shapes and 3! = 6 ways to assign the labels to each shape, so the count is 5 · 6 = 30.
Exercise
How many distinct BSTs on keys 1, 2, 3, 4 have height 3, meaning every level holds exactly one node?
Show answer
Each of the 3 non-root nodes is the left or right child of the previous node, so there are 2^3 = 8 such trees.
Exercise
Compute C6 from C5 = 42 using the ratio formula, then confirm it with the closed form.
Show answer
With n = 5, C_6 = 42 · 2(2·5+1)/(5+2) = 42 · 22/7 = 132. The closed form gives binomial(12, 6)/7 = 924/7 = 132.