fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n;
  6. cin>>n;
  7. vector<int> adjList[n];
  8. vector<int> visited(n);
  9. vector<int> child(n,-1);
  10. queue<int> q;
  11. for(int i=0;i<n-1;i++){
  12. int x,y;
  13. cin>>x>>y;
  14. adjList[x].push_back(y);
  15. adjList[y].push_back(x);
  16. }
  17. visited[0]=1;
  18. q.push(0);
  19. while(!q.empty()){
  20. int count=0;
  21. int node=q.front();
  22. // cout<<node<<" ";
  23. q.pop();
  24. for(auto adjNode : adjList[node]){
  25. if(!visited[adjNode]){
  26. q.push(adjNode);
  27. visited[adjNode]=1;
  28. count++;
  29. }
  30. }
  31. child[node]=count;
  32. }
  33. for(int i=0;i<child.size();i++){
  34. if(child[i]==0)
  35. cout<<"child of node "<<i<<" : "<<child[i]<<"\n";
  36. else
  37. cout<<"node "<<i<<" is a leaf node \n";
  38. }
  39. return 0;
  40. }
Success #stdin #stdout 0s 5348KB
stdin
7
0 1
0 2
1 3
1 4
2 5
2 6
stdout
node 0 is a leaf node 
node 1 is a leaf node 
node 2 is a leaf node 
child of node 3 : 0
child of node 4 : 0
child of node 5 : 0
child of node 6 : 0