# Number of leaf nodes in the subtree of every node of an n-ary tree in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the number of leaf nodes for every node in the n-ary tree.

Given a n-ary tree, we have to find the number of leaf nodes for every subtree. Let's see an example.

Input

N = 8
tree = [[2, 3], [], [4, 5, 6], [7, 8], [], [], [], []]

Output

1->5 2->1 3->4 4->2 5->1 6->1 7->1 8->1

## Algorithm

• Initialise the n-ary tree with tree you like.

• Use the DFS to traverse through the tree.

• Maintain an array to store the count of each node leaf nodes count.

• Increment the count of leaf node after the recursive call to DFS.

• Print all node with leaf nodes count.

## Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
void insertNode(int x, int y, vector<int> tree[]) {
tree[x].push_back(y);
}
void DFS(int node, int leaf[], int visited[], vector<int> tree[]) {
leaf[node] = 0;
visited[node] = 1;
for (auto it : tree[node]) {
if (!visited[it]) {
DFS(it, leaf, visited, tree);
leaf[node] += leaf[it];
}
}
if (!tree[node].size()) {
leaf[node] = 1;
}
}
int main() {
int N = 8;
vector<int> tree[N + 1];
insertNode(1, 2, tree);
insertNode(1, 3, tree);
insertNode(3, 4, tree);
insertNode(3, 5, tree);
insertNode(3, 6, tree);
insertNode(4, 7, tree);
insertNode(4, 8, tree);
int leaf[N + 1];
int visited[N + 1];
for (int i = 0; i <= N; i++) {
visited[i] = 0;
}
DFS(1, leaf, visited, tree);
for (int i = 1; i <= N; i++) {
cout << i << "->" << leaf[i] << endl;
}
return 0;
}

## Output

If you run the above code, then you will get the following result.

1->5
2->1
3->4
4->2
5->1
6->1
7->1
8->1
Updated on 26-Oct-2021 15:07:20