# Given a n-ary tree, count number of nodes which have more number of children than parents

Given a N-ary tree represented as adjacency list, we need to write a program to count all such nodes in this tree which has more number of children than its parent.

For Example, In the above tree, the count will be 1 as there is only one such node which is ‘2’ which has more number of children than its parent. 2 has three children (4, 5 and 6) whereas its parent, 1 has only two children (2 and 3).

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

We can solve this problem using both BFS and DFS algorithms. We will explain here in details about how to solve this problem using BFS algorithm.
As the tree is represented using adjacency list representation. So, for any node say ‘u’ the number of children of this node can be given as adj[u].size().
Now the idea is to apply BFS on the given tree and while traversing the children of a node ‘u’ say ‘v’ we will simply check is adj[v].size() > adj[u].size().

Below is the C++ implementation of above idea:

 `// C++ program to count number of nodes ` `// which has more children than its parent ` ` `  `#include ` `using` `namespace` `std; ` ` `  `// function to count number of nodes ` `// which has more children than its parent ` `int` `countNodes(vector<``int``> adj[], ``int` `root) ` `{     ` `    ``int` `count = 0; ` ` `  `    ``// queue for applying BFS ` `    ``queue<``int``> q; ` ` `  `    ``// BFS algorithm ` `    ``q.push(root); ` `     `  `    ``while` `(!q.empty()) ` `    ``{ ` `        ``int` `node = q.front(); ` `        ``q.pop(); ` ` `  `        ``// traverse children of node ` `        ``for``( ``int` `i=0;i adj[node].size()) ` `                ``count++; ` `            ``q.push(children); ` `        ``} ` `    ``} ` ` `  `    ``return` `count; ` `} ` ` `  `// Driver program to test above functions ` `int` `main() ` `{     ` `    ``// adjacency list for n-ary tree ` `    ``vector<``int``> adj; ` ` `  `    ``// construct n ary tree as shown ` `    ``// in above diagram ` `    ``adj.push_back(2); ` `    ``adj.push_back(3); ` `    ``adj.push_back(4); ` `    ``adj.push_back(5); ` `    ``adj.push_back(6); ` `    ``adj.push_back(9); ` `    ``adj.push_back(7); ` `    ``adj.push_back(8); ` ` `  `    ``int` `root = 1; ` ` `  `    ``cout << countNodes(adj, root); ` `    ``return` `0; ` `} `

Output:

```1
```

Time Complexity: O( n ) , where n is the number of nodes in the tree.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

This article is attributed to GeeksforGeeks.org

## tags:

Tree n-ary-tree Tree

code

load comments