fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner sc = new Scanner(System.in);
  13. int n = sc.nextInt(); // number of nodes
  14.  
  15. List<Integer>[] G = new List[n + 1];
  16. for (int i = 0; i <= n; i++) {
  17. G[i] = new ArrayList<>();
  18. }
  19.  
  20. // read n-1 edges
  21. for (int i = 1; i < n; i++) {
  22. int u = sc.nextInt();
  23. int v = sc.nextInt();
  24. G[u].add(v);
  25. G[v].add(u);
  26. }
  27.  
  28. int ans = -1;
  29. for (int i = 1; i <= n; i++) {
  30. if (G[i].size() == 1) {
  31. ans = i;
  32. break;
  33. }
  34. }
  35.  
  36. System.out.println(ans);
  37. }
  38. }
Success #stdin #stdout 0.14s 54544KB
stdin
5
1 2
1 3
3 4
3 5
stdout
2