題目:node
For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.app
Format The graph contains n nodes which are labeled from 0 to n - 1.
You will be given the number n and a list of undirected edges (each
edge is a pair of labels).codeYou can assume that no duplicate edges will appear in edges. Since all
edges are undirected, [0, 1] is the same as [1, 0] and thus will not
appear together in edges.orm
解法:
由於樹就是兩個點被一條線連接的無向圖,因此先用一個list把樹存成無向圖的列表。能夠從頭邊同時進行,查看葉子節點並加入到葉子節點鏈表(遍歷一遍後,葉子節點鏈表size 爲1)。 將葉子節點保存下來。這些葉子節點不用再查,可是剩餘的中間節點,要依次查看,把跟第一層葉子節點有關的圖的矩陣裏對應的記錄所有刪除,相似於剝除最外面一圈全部的點。 這個時候就會有第二層葉子節點(那些在列表當中size爲1的點),用一樣的方法進行剝除。最後留在葉子節點list裏面的點便可覺得根。rem
代碼:get
public List<Integer> findMinHeightTrees(int n, int[][] edges) { List<Integer> leaves = new ArrayList<>(); if (n == 1) { leaves.add(0); return leaves; } List<Set<Integer>> adj = new ArrayList<>(); for(int i = 0; i < n; i++) adj.add(new HashSet<>()); for(int[] edge : edges){ adj.get(edge[0]).add(edge[1]); adj.get(edge[1]).add(edge[0]); } for(int i = 0; i < n; i++) if(adj.get(i).size()==1) leaves.add(i); while(n > 2){ n-=leaves.size(); List<Integer> newLeaves = new ArrayList<>(); for(int i : leaves){ for(int j : adj.get(i)){ adj.get(j).remove(i); if(adj.get(j).size() ==1) newLeaves.add(j); } } leaves = newLeaves; } return leaves; }