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 dfs(int node,int[] used,int[] height,ArrayList<Integer>[] G,int[] parent) {
  11. used[node]=1;
  12. for(int child: G[node]) {
  13. if(used[child]==0){
  14. parent[child]=node;
  15. dfs(child,used,height,G,parent);
  16. }
  17. }
  18. int ht=0;
  19. for(int child:G[node]){
  20. if(child==parent[node]) {
  21. continue;
  22. }else{
  23. ht=Math.max(ht,height[child]);
  24. }
  25. }
  26. height[node]=ht+1;
  27.  
  28. }
  29. public static void main (String[] args) throws java.lang.Exception
  30. {
  31. Scanner sc=new Scanner(System.in);
  32. int n=sc.nextInt();//input of nodes
  33. ArrayList<Integer>[] G=new ArrayList[n+1];
  34. for(int i=1;i<=n;i++){
  35. G[i]=new ArrayList<>();
  36. }
  37. for(int i=1;i<n;i++){
  38. int u= sc.nextInt();
  39. int v= sc.nextInt();
  40. G[u].add(v);
  41. G[v].add(u);
  42. }
  43. ArrayList<Integer> ans=new ArrayList<>();
  44. int[] used=new int[n+1];
  45. int[] height=new int[n+1];
  46. int[] parent=new int[n+1];
  47. dfs(1,used,height,G,parent);
  48. for (int i=1;i<=n;i++){
  49. if(height[i]==1){
  50. ans.add(i);
  51. }
  52. }
  53. for(int x:ans){
  54. System.out.print(x);
  55. }
  56.  
  57. }
  58. }
Success #stdin #stdout 0.18s 54608KB
stdin
5
1 2
1 5
1 3
3 4
stdout
245