fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define endl '\n'
  4. #define int long long
  5. const int MOD = pow(10,9)+7;
  6. const int MOD2 = 998244353;
  7. const int INF = LLONG_MAX/2;
  8.  
  9. int primes[1000000];
  10.  
  11. void seive(){
  12. fill(primes, primes + 1000000, 1);
  13. primes[0] = primes[1] = 0;
  14. for(int i = 2 ; i*i < 1000000 ; i++){
  15. if(primes[i]){
  16. for(int j = i*i ; j < 1000000 ; j += i){
  17. primes[j] = 0;
  18. }
  19. }
  20. }
  21. for(int i = 1 ; i < 1000000 ; i++){
  22. primes[i] += primes[i-1];
  23. }
  24. }
  25. int factorial(int n){
  26. if(n==0){
  27. return 1;
  28. }
  29. return (n*(factorial(n-1)))%MOD;
  30. }
  31. bool isPrime(int n){
  32. if(n <= 1) return false;
  33. for(int i = 2 ; i*i <= n ; i++){
  34. if(n % i == 0) return false;
  35. }
  36. return true;
  37. }
  38.  
  39. int power(int a, int b){
  40. if(b == 0) return 1;
  41. a %= MOD;
  42. int value = power(a, b / 2);
  43. if(b % 2 == 0){
  44. return (value * value) % MOD;
  45. } else {
  46. return ((value * value) % MOD * (a % MOD)) % MOD;
  47. }
  48. }
  49.  
  50. int gcd(int a, int b){
  51. if(a == 0) return b;
  52. return gcd(b % a, a);
  53. }
  54. void solve() {
  55. int n1;
  56. cin>>n1;
  57. vector<int>A[n1+1];
  58. for(int i = 0 ; i<n1-1 ; i++){
  59. int a,b;
  60. cin>>a>>b;
  61. A[a].push_back(b);
  62. A[b].push_back(a);
  63. }
  64. queue<int>q;
  65. int visited[n1+1]={0};
  66. int children[n1+1] ={0};
  67. q.push(1);
  68. visited[1] = 1;
  69. while(!q.empty()){
  70. int node = q.front();
  71. q.pop();
  72. int cnt = 0;
  73. for(auto node1 : A[node]){
  74. if(!visited[node1]){
  75. cnt++;
  76. q.push(node1);
  77. visited[node1] = 1;
  78. }
  79. }
  80. children[node] = cnt;
  81. }
  82. for(int i = 1 ; i<n1+1 ; i++){
  83. cout<<"Node "<<i<<" has "<<children[i]<<" children"<<endl;
  84. }
  85. cout<<"The Leaf Nodes of the tree are as follows: ";
  86. for(int i = 1 ; i<n1+1 ; i++){
  87. if(children[i]==0){
  88. cout<<i<<" ";
  89. }
  90. }
  91. cout<<endl;
  92. }
  93.  
  94. signed main(){
  95. ios::sync_with_stdio(false); cin.tie(NULL);
  96. //int t;
  97. //cin >> t;
  98. //while(t--){
  99. solve();
  100. //}
  101. return 0;
  102. }
Success #stdin #stdout 0.01s 5320KB
stdin
5
1 2
2 3
3 4
4 5
stdout
Node 1 has 1 children
Node 2 has 1 children
Node 3 has 1 children
Node 4 has 1 children
Node 5 has 0 children
The Leaf Nodes of the tree are as follows: 5