310. 最小高度树

  1. class Solution {
  2. List<Integer> res = new ArrayList<Integer>();
  3. public List<Integer> findMinHeightTrees(int n, int[][] edges) {
  4. if (n == 1) {
  5. res.add(0);
  6. return res;
  7. }
  8. List<Integer>[] graph = new List[n];
  9. for (int i = 0; i < n; ++i) graph[i] = new ArrayList<Integer>();
  10. //创建图
  11. for (int[] edge : edges) {
  12. graph[edge[0]].add(edge[1]);
  13. graph[edge[1]].add(edge[0]);
  14. }
  15. int[] parent = new int[n];
  16. Arrays.fill(parent, -1);
  17. int x = findLongestNode(graph, 0, parent);
  18. int y = findLongestNode(graph, x, parent);
  19. List<Integer> path = new ArrayList<Integer>();
  20. parent[x] = -1;
  21. while (y != -1) {
  22. path.add(y);
  23. y = parent[y];
  24. }
  25. if (path.size() % 2 == 0) {
  26. res.add(path.get(path.size() / 2 - 1));
  27. res.add(path.get(path.size() / 2));
  28. } else {
  29. res.add(path.get(path.size() / 2));
  30. }
  31. return res;
  32. }
  33. public int findLongestNode(List<Integer>[] graph, int start, int[] parent) {
  34. int n = graph.length;
  35. boolean[] visit = new boolean[n];
  36. Queue<Integer> queue = new LinkedList<>();
  37. visit[start] = true;
  38. queue.offer(start);
  39. int node = -1;
  40. while(!queue.isEmpty()) {
  41. node = queue.poll();
  42. for (int i : graph[node]) {
  43. if (visit[i] == false) {
  44. visit[i] = true;
  45. parent[i] = node;
  46. queue.offer(i);
  47. }
  48. }
  49. }
  50. return node;
  51. }
  52. }