fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int main(){
  6. int n;
  7. cin>>n;
  8.  
  9. int m=n-1;
  10.  
  11. vector<vector<int>>graph(n);
  12. int i=1;
  13. while(i<=m){
  14. int x,y;
  15. cin>>x>>y;
  16. x--,y--;
  17. graph[x].push_back(y);
  18. graph[y].push_back(x);
  19.  
  20. i++;
  21. }
  22.  
  23. vector<int>child_cnt(n,0);
  24.  
  25. queue<int>q;
  26. int source=0;
  27. vector<bool>visited(n,false);
  28.  
  29. q.push(source);
  30. visited[source]=true;
  31.  
  32. while(!q.empty()){
  33. int parent=q.front();
  34. q.pop();
  35.  
  36. int count=0;
  37.  
  38. for(auto it:graph[parent]){
  39. if(!visited[it]){
  40. count++;
  41. visited[it]=true;
  42. q.push(it);
  43. }
  44. }
  45.  
  46. child_cnt[parent]=count;
  47.  
  48. }
  49.  
  50. for(int i=0;i<n;i++){
  51. if(child_cnt[i]==0){
  52. cout<<"Leaf node: "<<i+1<<endl;
  53. }
  54. }
  55.  
  56. for(int i=0;i<n;i++){
  57. cout<<"Node "<<i+1<<" has children: "<<child_cnt[i]<<endl;
  58. }
  59. return 0;
  60.  
  61. }
Success #stdin #stdout 0.01s 5252KB
stdin
5 
1 2
2 3 
3 4 
4 5 
stdout
Leaf node: 5
Node 1 has children: 1
Node 2 has children: 1
Node 3 has children: 1
Node 4 has children: 1
Node 5 has children: 0