Counting binary trees
How many binary trees have n nodes (the Catalan number), how many with labels, how many binary search trees, how many full trees, how many trees of a given height, how many heaps and how many insertion orders build one search tree. The recurrence, the closed form, and the tables GATE asks for are all run and checked by programs.
Why it exists
"How many different binary trees can be formed with nodes?" is one of the most repeated questions in the tree topic, in several disguises: unlabelled, labelled, search trees, full trees, trees of a given height, heaps. The answers are all built from the same recurrence, so once you can derive it you do not need to memorise a table. This page derives it once and then applies it.
Prerequisites
Precise definitions
A binary tree here is as defined on the trees page: every node has a left and a right child slot, each of which may be empty, and swapping the sides gives a different tree. Two trees are the same if they have the same shape (and, for labelled trees, the same label at each position).
The recurrence
Let be the number of binary trees with nodes (shapes only). The empty tree counts as one, so . A tree with nodes has a root, a left subtree with nodes and a right subtree with nodes, for some from to . The two subtrees are chosen independently, so
This gives and the closed form
This closed form is not derived on this page (the standard proof uses generating functions or a ballot-sequence argument; CLRS Problem 12-4 walks through one). Here it is checked against the recurrence by a program, and for GATE you only need to know it and the first values. These are the Catalan numbers. They grow like divided by a power of , so they are exponential.
Variants
| Question | Count | Reason |
|---|---|---|
| Binary trees with nodes (unlabelled) | the recurrence above | |
| Binary trees with distinct labels (each tree with every assignment of labels) | choose the shape, then label the positions in any order | |
| Binary search trees on distinct keys | for each shape there is exactly one way to place the sorted keys | |
| BSTs on keys whose root is key | keys below go left, keys above go right | |
| Full binary trees (0 or 2 children) with internal nodes (so nodes) | ||
| Binary trees with a given preorder (or inorder, or postorder) of distinct keys | see construction | |
| Orders in which a stack can output pushed in order | see stack | |
| Ordered (plane) rooted trees with nodes | the left-child right-sibling correspondence | |
| Well-formed bracket sequences with pairs | ||
| Ways to triangulate a convex -gon |
Trees of a given height
Let be the number of binary trees with nodes and height at most (height of the empty tree ). Then for , for , and
The number with height exactly is . The extremes: the chain shapes number (each of the non-root nodes is a left or a right child of the one above), and the smallest height is .
Counting orders, not shapes
- The number of insertion orders of distinct keys that build one particular binary search tree is where is the number of nodes in the subtree of (counting ). The reason: in any valid order every node must come before all the other nodes of its subtree, and the fraction of orders in which each node precedes the rest of its subtree is . (This is a sketch: it uses that these events are independent for different nodes. The formula itself was checked by brute force for , and summing over all shapes does give .)
- The same formula counts the heaps: the number of ways to put the keys into the complete binary tree of nodes so that every parent is larger than its children is over that complete tree.
How it works
Everything on this page is one idea: split on the root. Choose the size of the left subtree, count the ways for each side independently, multiply, and add over the choices of size. Labelled counts add one more factor (which labels go left: a binomial coefficient). The recurrences are run below.
Worked examples
EX 1Catalan numbers from the recurrence, the closed form, and full trees
Easy#include <stdio.h>
int main(void) {
long c[9] = {1};
for (int n = 1; n <= 8; n++) {
c[n] = 0;
for (int i = 0; i < n; i++) c[n] += c[i] * c[n - 1 - i];
}
int ok = 1;
for (int n = 0; n <= 8; n++) {
long b = 1;
for (int i = 1; i <= n; i++) b = b * (n + i) / i;
ok = ok && b / (n + 1) == c[n];
}
long f[10] = {0};
f[1] = 1;
for (int n = 3; n <= 9; n += 2)
for (int i = 1; i < n - 1; i += 2) f[n] += f[i] * f[n - 1 - i];
for (int n = 0; n <= 8; n++) printf("%ld ", c[n]);
printf("\n%d\n%ld %ld %ld %ld %ld\n", ok, f[1], f[3], f[5], f[7], f[9]);
return 0;
}Output:
1 1 2 5 14 42 132 429 1430
1
1 1 2 5 14Reading it. The first line is the recurrence evaluated for . The second line says the closed form gave the same numbers. The third line counts full binary trees (every node 0 or 2 children) with nodes: a full tree has an odd number of nodes, and the counts are the Catalan numbers , because a full tree with internal nodes has nodes. So the answer to "how many full binary trees with 9 nodes" is .
EX 2Binary trees with distinct labels
Medium#include <stdio.h>
int main(void) {
long binom[8][8] = {{0}};
for (int n = 0; n < 8; n++) {
binom[n][0] = 1;
for (int k = 1; k <= n; k++) binom[n][k] = binom[n - 1][k - 1] + (k <= n - 1 ? binom[n - 1][k] : 0);
}
long l[7] = {1};
for (int n = 1; n <= 5; n++) {
long s = 0;
for (int k = 0; k < n; k++) s += binom[n - 1][k] * l[k] * l[n - 1 - k];
l[n] = n * s;
}
long c[6] = {1}, fact = 1;
for (int n = 1; n <= 5; n++) {
c[n] = 0;
for (int i = 0; i < n; i++) c[n] += c[i] * c[n - 1 - i];
}
int ok = 1;
for (int n = 1; n <= 5; n++) {
fact *= n;
ok = ok && l[n] == fact * c[n];
}
printf("%ld %ld %ld %ld %ld\n%d\n", l[1], l[2], l[3], l[4], l[5], ok);
return 0;
}Output:
1 4 30 336 5040
1Reading it. For distinct labels, pick the root ( ways), pick which of the other labels go to the left subtree ( ways), and count the labelled trees on each side: . The values 1, 4, 30, 336, 5040 equal (, , , ), which the second line confirms. The easy way: count the shapes () and multiply by the ways to put labels on them.
EX 3Binary search trees by root
Medium#include <stdio.h>
int main(void) {
long c[6] = {1};
for (int n = 1; n <= 5; n++) {
c[n] = 0;
for (int i = 0; i < n; i++) c[n] += c[i] * c[n - 1 - i];
}
long total = 0;
for (int k = 1; k <= 5; k++) {
long w = c[k - 1] * c[5 - k];
total += w;
printf("%ld ", w);
}
printf("%ld\n", total);
return 0;
}Output:
14 5 4 5 14 42Reading it. Among the BSTs on the keys 1 to 5, those with root 1 have an empty left side and a right subtree on 4 keys: . Root 2: . Root 3: . Root 4: . Root 5: . The total is . A GATE question that fixes the root or the root of the left subtree is applying the same product rule.
EX 4Counting heaps by trying every arrangement
GATE level#include <stdio.h>
static int n, p[8];
static int count(int used, int k) {
if (k == n) return 1;
int t = 0;
for (int v = 1; v <= n; v++) {
if (used & (1 << v)) continue;
if (k > 0 && p[(k - 1) / 2] < v) continue;
p[k] = v;
t += count(used | (1 << v), k + 1);
}
return t;
}
int main(void) {
for (n = 3; n <= 7; n++) printf("%d ", count(0, 0));
printf("\n");
return 0;
}Output:
2 3 8 20 80Reading it. The program fills an array from position 0, where position has its parent at , and only allows a key smaller than its parent. For to the number of ways to arrange the keys in a max-heap is 2, 3, 8, 20, 80. Check with the formula for the complete tree with 7 nodes: subtree sizes are 7, 3, 3, 1, 1, 1, 1 (product 63), so . For : sizes 5, 3, 1, 1, 1, product 15, and .
EX 5Binary trees of each height
GATE level#include <stdio.h>
static long a[8][9];
int main(void) {
for (int h = 0; h <= 8; h++) a[0][h] = 1;
for (int n = 1; n <= 7; n++)
for (int h = 1; h <= 8; h++)
for (int i = 0; i < n; i++) a[n][h] += a[i][h - 1] * a[n - 1 - i][h - 1];
for (int h = 3; h <= 5; h++) printf("%ld ", a[5][h] - a[5][h - 1]);
printf("\n");
for (int h = 3; h <= 7; h++) printf("%ld ", a[7][h] - a[7][h - 1]);
printf("\n");
return 0;
}Output:
6 20 16
1 68 152 144 64Reading it. Here a[n][h] stores the number of binary trees with nodes and height at most (the index is shifted by one so that the empty-tree height is index 0), so the difference a[n][h] - a[n][h-1] is the number of trees of height exactly , and the loops print heights 2, 3, 4 (first line) and 2 to 6 (second line). The first line shows the 42 binary trees with 5 nodes by height: 6 of height 2, 20 of height 3, 16 of height 4; they add up to 42, and the 16 chains of height 4 equal . The second line shows the 7-node trees by height 2 to 6: exactly 1 perfect tree (height 2), and chains (height 6); the five counts add to 429.
EX 6Using the formulas
GATE level(a) How many distinct binary search trees can store the keys ? .
(b) How many binary trees with 3 unlabelled nodes? . With 3 labelled nodes (labels all used)? .
(c) How many binary trees have nodes and a left subtree with exactly 2 nodes? The left subtree can be any of shapes and the right subtree has 3 nodes ( shapes): .
(d) How many different insertion orders of build the perfect BST (root 4)? . For the chain that grows to the right: (only the sorted order).
(e) A full binary tree has 21 nodes. The number of such trees is , because it has 10 internal nodes. .
(f) How many binary trees of nodes have height exactly 3? The chains: .
Cheat box
Cheat box
- Recurrence: , . Closed form .
- Values: for .
- Unlabelled binary trees, BSTs on keys, full trees with internal nodes, trees sharing a preorder, stack permutations, bracket sequences: all .
- Labelled binary trees: .
- BSTs on with root : .
- Chains (height ): . Only one perfect tree when .
- Insertion orders giving one BST, and heaps on the complete tree: .
- Height-limited count: .
Traps and GATE patterns
Connections
Builds on
Across subjects
Counting trees uses the same sum-of-products idea as recurrence relations. The connection to stack-sortable permutations is on the stack and construction pages, and the order counts are used for the binary search tree and the binary heap. The basic facts that this page builds on are on the trees page.
PYQs
12 previous year questions from your book. I re-solved each one myself (9 by running or simulating, 3 by reasoning only); the book's key is shown next to my answer. All PYQs
The height of a binary tree is the number of edges in the longest path from the root to a leaf in the tree. The maximum possible height of a full binary tree with 23 nodes is . (answer in integer)
Let T be a full binary tree with 8 leaves. (A full binary tree has every level full.) Suppose two leaves a and b of T are chosen uniformly and independently at random. The expected value of the distance between a and b in T (i.e., the number of edges in the unique path between a and b) is (rounded off to 2 decimal places)
Let T be a binary search tree with 15 nodes. The minimum and maximum possible heights of T are: Note: The height of a tree with a single node is 0.
- (a)4 and 15 respectively
- (b)3 and 14 respectively
- (c)4 and 14 respectively
- (d)3 and 15 respectively
A binary tree T has 20 leaves. The number of nodes in T having two children is .
- (a)19
- (b)20
- (c)21
- (d)22
The number of ways in which the numbers 1, 2, 3, 4, 5, 6, 7 can be inserted in an empty binary search tree, such that the resulting tree has height 6, is DATA STRUCTURE Note: The height of a tree with a single node is 0. [This question was originally a Fill-in-the-Blanks question]
- (a)2
- (b)4
- (c)64
- (d)32
Consider a binary tree T that has 200 leaf nodes. Then, the number of nodes in T that have exactly two children are
- (a)199
- (b)198
- (c)197
- (d)196
The height of a tree is the length of the longest root- to-leaf path in it. The maximum and minimum number of nodes in a binary tree of height 5 are
- (a)63 and 6, respectively
- (b)64 and 5, respectively
- (c)32 and 6, respectively
- (d)31 and 5, respectively
The height of a binary tree is the maximum number of edges in any root to leaf path. The maximum number of nodes in a binary tree of height h is:
- (a)2h-1
- (b)2h-1-1
- (c)2h+1-1
- (d)2h+1
The maximum number of binary trees that can be formed with three unlabeled nodes is:
- (a)1
- (b)5
- (c)4
- (d)3
A complete n-ary tree is a tree in which each node has n children or no children. Let I be the number of internal nodes and L be the number of leaves in a complete n-ary tree. If L = 41, and I = 10, what is the value of n?
- (a)3
- (b)4
- (c)5
- (d)6
How many distinct binary search trees can be created out of 4 distinct keys?
- (a)5
- (b)14
- (c)24
- (d)42
In a complete k-ary tree, every internal node has exactly k children. The number of leaves in such a tree with n internal nodes is:
- (a)nk
- (b)(n - 1)k + 1
- (c)n(k - 1) + 1
- (d)n(k - 1)
Self-check
Question 1
How many different binary search trees can be formed from the keys 10, 20, 30, 40, 50? How many of them have 30 at the root?
Show answerHide
. With root 30 (the third key), two keys go left and two go right: .
Question 2
How many binary trees with 4 unlabelled nodes have height 2 (the minimum)? And how many have height 3?
Show answerHide
Height 3 is the chains: . All trees have height 2 or 3 (a 4-node tree needs height at least 2), so height 2 has .
Question 3
A full binary tree has 15 nodes. How many such trees are there?
Show answerHide
15 nodes means internal nodes, so the count is .
Question 4
In how many orders can the keys 1 to 3 be inserted into an empty BST so that the final tree has root 2?
Show answerHide
The tree is the balanced one with root 2 and children 1 and 3. Subtree sizes are 3, 1, 1, so orders: 2, 1, 3 and 2, 3, 1 (the root must be first).
Question 5
How many binary trees have preorder 1 2 3 4?
Show answerHide
(distinct keys, one traversal given).
Revision card
One-screen revision
- ; ; .
- Unlabelled binary trees, BSTs, full trees with internal nodes, trees with a given preorder (or inorder, or postorder) alone, stack permutations: . A preorder together with an inorder pins down at most one tree.
- Labelled: . BST with root : .
- Chains: . Insertion orders for one BST, heaps on a complete shape: .
- Split on the root; multiply independent sides; add over sizes.
References
- ·Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, 3rd ed., Section 12.4 Randomly built binary search trees (expected height); Problem 12-4 Number of different binary trees (the Catalan count; both from memory)
Verification
All C programs on this page are compiled with -Wall -Wextra -Werror and run by npm run verify:c, also under AddressSanitizer and UBSan: they compute the Catalan numbers from the recurrence and from the closed form, the labelled counts, the BST counts per root, the heap counts by a pruned backtracking search that enforces parent > child as it fills the array (limited to n <= 7), and the number of trees of each height. The statement that the number of insertion orders producing a given BST shape is n! divided by the product of all subtree sizes, and that the number of shapes equals the Catalan number, was checked by trying every insertion order of 1..n for n up to 7 in a one-off script that is not part of the repository. The textbook section numbers were written from memory and have NOT been checked against the book. The prose and the GATE-pattern claims have NOT yet had a human textbook check (the independent second pass is described at the end of these notes). SECOND PASS (2026-11-02, done by the assistant, not a human check): every Self-check question was solved before the printed answer was read and all agreed; the definitions, worked examples, cheat box and traps were read claim by claim and the numbers re-derived by hand (long C programs were not re-read line by line: they are compiled and compared by npm run verify:c, and their printed outputs were checked against the prose). No defect found. Status raised to self-checked; verified needs a textbook or human check.
last verified: never
My notes (saved in this browser)