G27
Self-checkedTier 1 16 min readpds.binary-tree-counting

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 nn 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

Trees and binary trees
Counting: permutations and combinationsplanned

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 CnC_n be the number of binary trees with nn nodes (shapes only). The empty tree counts as one, so C0=1C_0 = 1. A tree with n≥1n \ge 1 nodes has a root, a left subtree with ii nodes and a right subtree with n−1−in - 1 - i nodes, for some ii from 00 to n−1n - 1. The two subtrees are chosen independently, so

Cn=∑i=0n−1Ci Cn−1−i.C_n = \sum_{i=0}^{n-1} C_i \, C_{n-1-i}.

This gives C0,C1,C2,…=1,1,2,5,14,42,132,429,1430,…C_0, C_1, C_2, \ldots = 1, 1, 2, 5, 14, 42, 132, 429, 1430, \ldots and the closed form

Cn=1n+1(2nn).C_n = \frac{1}{n+1}\binom{2n}{n}.

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 4n4^n divided by a power of nn, so they are exponential.

Variants

QuestionCountReason
Binary trees with nn nodes (unlabelled)CnC_nthe recurrence above
Binary trees with nn distinct labels (each tree with every assignment of labels)n!⋅Cn=(2n)!(n+1)!n! \cdot C_n = \dfrac{(2n)!}{(n+1)!}choose the shape, then label the nn positions in any order
Binary search trees on nn distinct keysCnC_nfor each shape there is exactly one way to place the sorted keys
BSTs on keys 1..n1..n whose root is key kkCk−1⋅Cn−kC_{k-1} \cdot C_{n-k}keys below kk go left, keys above go right
Full binary trees (0 or 2 children) with nn internal nodes (so 2n+12n + 1 nodes)CnC_n
Binary trees with a given preorder (or inorder, or postorder) of nn distinct keysCnC_nsee construction
Orders in which a stack can output 1..n1..n pushed in orderCnC_nsee stack
Ordered (plane) rooted trees with n+1n + 1 nodesCnC_nthe left-child right-sibling correspondence
Well-formed bracket sequences with nn pairsCnC_n
Ways to triangulate a convex (n+2)(n+2)-gonCnC_n

Trees of a given height

Let A(n,h)A(n, h) be the number of binary trees with nn nodes and height at most hh (height of the empty tree −1-1). Then A(0,h)=1A(0, h) = 1 for h≥−1h \ge -1, A(n,−1)=0A(n, -1) = 0 for n≥1n \ge 1, and

A(n,h)=∑i=0n−1A(i,h−1) A(n−1−i,h−1).A(n, h) = \sum_{i=0}^{n-1} A(i, h-1)\, A(n-1-i, h-1).

The number with height exactly hh is A(n,h)−A(n,h−1)A(n, h) - A(n, h-1). The extremes: the chain shapes number 2n−12^{n-1} (each of the n−1n - 1 non-root nodes is a left or a right child of the one above), and the smallest height is ⌈log⁡2(n+1)⌉−1\lceil \log_2(n+1) \rceil - 1.

Counting orders, not shapes

  • The number of insertion orders of nn distinct keys that build one particular binary search tree TT is n!∏vs(v),\frac{n!}{\prod_{v} s(v)}, where s(v)s(v) is the number of nodes in the subtree of vv (counting vv). 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 1/s(v)1/s(v). (This is a sketch: it uses that these events are independent for different nodes. The formula itself was checked by brute force for n≤7n \le 7, and summing over all shapes does give n!n!.)
  • The same formula counts the heaps: the number of ways to put the keys 1..n1..n into the complete binary tree of nn nodes so that every parent is larger than its children is n!/∏vs(v)n! / \prod_v s(v) 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 14

Reading it. The first line is the recurrence Cn=∑CiCn−1−iC_n = \sum C_i C_{n-1-i} evaluated for n=0..8n = 0..8. The second line says the closed form 1n+1(2nn)\frac{1}{n+1}\binom{2n}{n} gave the same numbers. The third line counts full binary trees (every node 0 or 2 children) with 1,3,5,7,91, 3, 5, 7, 9 nodes: a full tree has an odd number of nodes, and the counts 1,1,2,5,141, 1, 2, 5, 14 are the Catalan numbers C0,…,C4C_0, \ldots, C_4, because a full tree with mm internal nodes has 2m+12m + 1 nodes. So the answer to "how many full binary trees with 9 nodes" is C4=14C_4 = 14.

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
1

Reading it. For nn distinct labels, pick the root (nn ways), pick which kk of the other n−1n - 1 labels go to the left subtree ((n−1k)\binom{n-1}{k} ways), and count the labelled trees on each side: L(n)=n∑k(n−1k)L(k)L(n−1−k)L(n) = n \sum_k \binom{n-1}{k} L(k) L(n-1-k). The values 1, 4, 30, 336, 5040 equal n!⋅Cnn! \cdot C_n (2⋅2=42 \cdot 2 = 4, 6⋅5=306 \cdot 5 = 30, 24⋅14=33624 \cdot 14 = 336, 120⋅42=5040120 \cdot 42 = 5040), which the second line confirms. The easy way: count the shapes (CnC_n) and multiply by the n!n! 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 42

Reading 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: C0C4=14C_0 C_4 = 14. Root 2: C1C3=5C_1 C_3 = 5. Root 3: C2C2=4C_2 C_2 = 4. Root 4: 55. Root 5: 1414. The total is C5=42C_5 = 42. 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 80

Reading it. The program fills an array from position 0, where position kk has its parent at (k−1)/2(k - 1)/2, and only allows a key smaller than its parent. For n=3n = 3 to 77 the number of ways to arrange the keys 1..n1..n in a max-heap is 2, 3, 8, 20, 80. Check with the formula n!/∏s(v)n! / \prod s(v) for the complete tree with 7 nodes: subtree sizes are 7, 3, 3, 1, 1, 1, 1 (product 63), so 5040/63=805040 / 63 = 80. For n=5n = 5: sizes 5, 3, 1, 1, 1, product 15, and 120/15=8120/15 = 8.

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 64

Reading it. Here a[n][h] stores the number of binary trees with nn nodes and height at most h−1h - 1 (the index is shifted by one so that the empty-tree height −1-1 is index 0), so the difference a[n][h] - a[n][h-1] is the number of trees of height exactly h−1h - 1, 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 25−12^{5-1}. The second line shows the 7-node trees by height 2 to 6: exactly 1 perfect tree (height 2), and 26=642^6 = 64 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 1,2,3,41, 2, 3, 4? C4=14C_4 = 14.

(b) How many binary trees with 3 unlabelled nodes? C3=5C_3 = 5. With 3 labelled nodes (labels A,B,CA, B, C all used)? 3!⋅5=303! \cdot 5 = 30.

(c) How many binary trees have n=6n = 6 nodes and a left subtree with exactly 2 nodes? The left subtree can be any of C2=2C_2 = 2 shapes and the right subtree has 3 nodes (C3=5C_3 = 5 shapes): 2⋅5=102 \cdot 5 = 10.

(d) How many different insertion orders of 1,2,3,4,5,6,71, 2, 3, 4, 5, 6, 7 build the perfect BST (root 4)? 7!/(7⋅3⋅3⋅1⋅1⋅1⋅1)=5040/63=807!/(7 \cdot 3 \cdot 3 \cdot 1 \cdot 1 \cdot 1 \cdot 1) = 5040/63 = 80. For the chain that grows to the right: 7!/(7⋅6⋅5⋅4⋅3⋅2⋅1)=17!/(7 \cdot 6 \cdot 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1) = 1 (only the sorted order).

(e) A full binary tree has 21 nodes. The number of such trees is C10C_{10}, because it has 10 internal nodes. C10=16796C_{10} = 16796.

(f) How many binary trees of n=4n = 4 nodes have height exactly 3? The chains: 24−1=82^{4-1} = 8.

Cheat box

Cheat box

  • Recurrence: Cn=∑i=0n−1CiCn−1−iC_n = \sum_{i=0}^{n-1} C_i C_{n-1-i}, C0=1C_0 = 1. Closed form 1n+1(2nn)\frac{1}{n+1}\binom{2n}{n}.
  • Values: 1,1,2,5,14,42,132,429,1430,4862,167961, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796 for n=0,1,…,10n = 0, 1, \ldots, 10.
  • Unlabelled binary trees, BSTs on nn keys, full trees with nn internal nodes, trees sharing a preorder, stack permutations, bracket sequences: all CnC_n.
  • Labelled binary trees: n!⋅Cn=(2n)!(n+1)!n! \cdot C_n = \frac{(2n)!}{(n+1)!}.
  • BSTs on 1..n1..n with root kk: Ck−1Cn−kC_{k-1} C_{n-k}.
  • Chains (height n−1n - 1): 2n−12^{n-1}. Only one perfect tree when n=2h+1−1n = 2^{h+1} - 1.
  • Insertion orders giving one BST, and heaps on the complete tree: n!/∏vs(v)n! / \prod_v s(v).
  • Height-limited count: A(n,h)=∑A(i,h−1)A(n−1−i,h−1)A(n, h) = \sum A(i, h-1) A(n-1-i, h-1).

Traps and GATE patterns

Connections

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

GATE 2026 · Set 1Q1 · page 66 of the book
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)
GATE 2019 · NATQ14 · page 68 of the book
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)
GATE 2017 · MCQ · 2 marksQ16 · page 68 of the book
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
GATE 2017 · MCQ · 1 markQ17 · page 68 of the book
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
GATE 2016 · Set 2 · MCQQ20 · page 68 of the book
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
GATE 2015Q24 · page 69 of the book
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
GATE 2015Q25 · page 69 of the book
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
GATE 2007Q41 · page 73 of the book
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
GATE 2007Q42 · page 73 of the book
The maximum number of binary trees that can be
formed with three unlabeled nodes is:
  • (a)1
  • (b)5
  • (c)4
  • (d)3
GATE 2007Q44 · page 73 of the book
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
GATE 2005Q51 · page 74 of the book
How many distinct binary search trees can be
created out of 4 distinct keys?
  • (a)5
  • (b)14
  • (c)24
  • (d)42
GATE 2005 · NATQ52 · page 74 of the book
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 answer

C5=42C_5 = 42. With root 30 (the third key), two keys go left and two go right: C2⋅C2=2⋅2=4C_2 \cdot C_2 = 2 \cdot 2 = 4.

Question 2

How many binary trees with 4 unlabelled nodes have height 2 (the minimum)? And how many have height 3?

Show answer

Height 3 is the chains: 23=82^{3} = 8. All C4=14C_4 = 14 trees have height 2 or 3 (a 4-node tree needs height at least 2), so height 2 has 14−8=614 - 8 = 6.

Question 3

A full binary tree has 15 nodes. How many such trees are there?

Show answer

15 nodes means m=7m = 7 internal nodes, so the count is C7=429C_7 = 429.

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 answer

The tree is the balanced one with root 2 and children 1 and 3. Subtree sizes are 3, 1, 1, so 3!/3=23!/3 = 2 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 answer

C4=14C_4 = 14 (distinct keys, one traversal given).

Revision card

One-screen revision

  • Cn=∑CiCn−1−iC_n = \sum C_i C_{n-1-i}; Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n}; 1,1,2,5,14,42,132,429,14301, 1, 2, 5, 14, 42, 132, 429, 1430.
  • Unlabelled binary trees, BSTs, full trees with nn internal nodes, trees with a given preorder (or inorder, or postorder) alone, stack permutations: CnC_n. A preorder together with an inorder pins down at most one tree.
  • Labelled: n! Cnn! \, C_n. BST with root kk: Ck−1Cn−kC_{k-1} C_{n-k}.
  • Chains: 2n−12^{n-1}. Insertion orders for one BST, heaps on a complete shape: n!/∏s(v)n!/\prod s(v).
  • 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