thumb_up 1 thumb_down 1 flag 0

To store such a tree we could make use of an adjacency list to store the nodes while storing we can represent A as a node with number 0, B with number 1 and so on and then after making the tree do a bfs traversal to print the count of the children nodes for each node.

 

#include <bits/stdc++.h>
using namespace std;

int main() {
	
	vector<int> g[10001];
	bool vis[10001];
	memset(vis,false,sizeof vis);
	
	int N; /*N represent no of edges */
	cin>>N;

    /* taking inputs */
	for(int i=0;i<N;i++)
	{
		char a,b;  
		cin>>a>>b;
		
		g[a-'A'].push_back(b-'A');
	}
	
	
	/*Using bfs to find the child counts*/
	
	queue<int> q;
	q.push(0);
	
	vis[0]=true;
	
	while(!q.empty())
	{
		int r = q.front();
		q.pop();
		vis[r]=true;
		cout<<(char)(r+'A')<<" has "<<g[r].size()<<" Child "<<endl;
		for(int i=0;i<g[r].size();i++)
		{
			if(!vis[g[r][i]])
				q.push(g[r][i]);
		}
	}
	
	return 0;
}