# Enumeration of Binary Trees in C++

C++Server Side ProgrammingProgramming

Enumeration of Binary Tree is counting the total number of distinct unlabeled binary trees of a given size (specific number of nodes). In this article, we will create a program to count the number of Binary Trees of n nodes.

## Based on labeling of nodes of binary tree, it is of two types:

• Labeled Binary Tree
• Unlabeled Binary Tree

Labeled Binary Tree: It is a binary Tree in which the nodes of a tree are labeled with values.

## Different Type of Labeled Binary Tree for a given number of nodes :

Number of nodes N = 2

Similarly, We can find the number of distinct labeled binary Tree for N number of nodes,

N = 1, count = 1

N = 2, count = 4
N = 3, count = 30

N = 4, count = 336

Here, we can see for each of the labeled nodes all the type of arrangements made for unlabeled nodes are made. So, the count will be n! * count of unlabeled binary trees.

C(N) = n! * ( (2n!) / (n+1)! * n! ) )

## Example

Live Demo

#include <iostream>
using namespace std;

int fact(int n){
if(n == 1)
return 1;
return n * fact(n - 1);
}

int distinctCountLabeledTree(int N){
return ( (fact(N))*( fact(2*N) / ( fact(N+1)*fact(N)) ) ) ;
}

int main(){

int N = 6;
cout<<"The number of Distinct labeled Binary Tree is "<<distinctCountLabeledTree(N);
return 0;
}

## Output −

The number of Distinct labeled Binary Tree is 95040

Unlabeled Binary Tree: It is a binary Tree in which the nodes of a tree are not labeled with values .

## Different type of Unlabeled binary Tree for a given number of nodes:

Number of Nodes N = 2

Number of distinct unlabeled binary Tree = 2

Similarly, We can find the number of distinct unlabeled binary trees for N.

N = 1, count = 1
N = 2, count = 2
N = 3, count = 5
N = 4, count = 14

Using this we can formulate the number of distinct unlabeled binary tree for N nodes,

It is given by Catalan number,

Another formula can be,

C(N) = (2n!) / (n+1)! * n!

## Example

Live Demo

#include <iostream>
using namespace std;

int fact(int n){
if(n == 1)
return 1;
return n * fact(n - 1);
}

int distinctCount(int N){
return ( fact(2*N) / ( fact(N+1)*fact(N) ) );
}

int main(){

int N = 7;
cout<<"The number of Distinct unlabeled Binary Tree is "<<distinctCount(N);
return 0;
}

## Output −

The number of Distinct unlabeled Binary Tree is 6