fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n;
  6. cin >> n;
  7.  
  8. if (n == 1) {
  9. return 0;
  10. // if the tree has 1 node. the question is already solved.
  11. }
  12.  
  13. vector<vector<int>> adj(n + 1);
  14.  
  15. for (int i = 0; i < n - 1; ++i) {
  16. int u, v;
  17. cin >> u >> v;
  18. adj[u].push_back(v);
  19. adj[v].push_back(u);
  20. }
  21.  
  22. int root;
  23. cin >> root;
  24.  
  25. if(adj[root].size() <= 2){
  26. return 0;
  27. // if the root has less than or equal to two nodes it also means that the question is solved.
  28. }
  29.  
  30.  
  31. bool found_leaf = false;
  32. for (int i = 1; i <= n; ++i) {
  33.  
  34. if (adj[i].size() == 1) {
  35. cout << "The leaf node which is now root node: "<< i << endl;
  36. root = i;
  37. found_leaf = true;
  38. break;
  39. }
  40. }
  41.  
  42. if (!found_leaf) {
  43. cout << "Invalid Tree" << endl;
  44. }
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 5312KB
stdin
5
1 2
1 3
1 4
2 5
1
stdout
The leaf node which is now root node: 3