1. 程式人生 > >310. Minimum Height Trees

310. Minimum Height Trees

eps spec sum style trees try findmi connected trie

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.

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). You 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. Example 1: Given n = 4
, edges = [[1, 0], [1, 2], [1, 3]] 0 | 1 / 2 3 return [1] Example 2: Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]] 0 1 2 \ | / 3 | 4 | 5 return [3, 4] Note: (1) According to the definition of tree on Wikipedia: “a tree is
an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.” (2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Credits: Special thanks to @dietpepsi for adding this problem and creating all test cases.

剪枝法, 不能用隊, 用剩余節點個數做while循環, 建立葉結點的容器當作隊, 需要更新葉結點容器不能用隊.

錯誤的做法: 跟207 Course Schedule有區別, 不能一味套, 因為這是無向圖

public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        if (n == 1) return Collections.singletonList(0);
        List<Integer> leaves = new ArrayList<>();
        List[] adj = new ArrayList[n];
        int[] indeg = new int[n];
        for (int i = 0; i < n; i++) {

            adj[i] = new ArrayList<Integer>();
        }
            
        for (int[] edge : edges) {
            adj[edge[0]].add(edge[1]);
            adj[edge[1]].add(edge[0]);
            indeg[edge[0]]++;
            indeg[edge[1]]++;
        }
        for (int i = 0; i < n; i++) {
            if (indeg[i] == 1) {
                leaves.add(i);
            }
        }
while (n > 2) { n -= leaves.size(); List<Integer> newList = new ArrayList<>(); for (int i : leaves) { int j = (int)adj[i].get(0); indeg[j]--; if (indeg[j] == 1) { newList.add(j); } } leaves = newList; } return leaves; } }

 應改為:, 因為get(0) 不一定get到當前葉節點的下一個內靠的葉結點, 可能是已經遍歷過得呢

while (n > 2) {
            n -= leaves.size();
            List<Integer> newList = new ArrayList<>();
            for (int i : leaves) {
                 ArrayList<Integer> list = adj[i];
                 for (Integer k : list) {
                       
                        indeg[k]--;
                        if (indeg[k] == 1) {
                            newList.add(k);
                        }
                    }
                     
            }
            leaves = newList;
        }

跟其最接近的題目是Course Schedule 課程清單和Course Schedule II 課程清單之二。由於LeetCode中的樹的題目主要都是針對於二叉樹的,而這道題雖說是樹但其實本質是想考察圖的知識,  

用的hashmap 來替代arraylist[]: 這樣的好處是方便鍵不是順序的時候, 與數組本質是一樣的, 但是存儲的鍵更靈活, 應該學會用map

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> leaves = new ArrayList<Integer>();
        if (edges==null || edges.length==0) {
            leaves.add(n-1);
            return leaves;
        }
        HashMap<Integer, ArrayList<Integer>> graph = new HashMap<Integer, ArrayList<Integer>>();
        int[] indegree = new int[n];
        
        for (int i=0; i<n; i++) {
            graph.put(i, new ArrayList<Integer>());
        }
        
        //build the graph
        for (int[] edge : edges) {
            graph.get(edge[0]).add(edge[1]);
            graph.get(edge[1]).add(edge[0]);
            indegree[edge[0]]++;
            indegree[edge[1]]++;
        }
        
        //find the leaves
        for (int i=0; i<n; i++) {
            if (indegree[i] == 1) {
                leaves.add(i);
            }
        }
        
        //topological sort until n<=2
        while (n > 2) {
            List<Integer> newLeaf = new ArrayList<Integer>();
            for (Integer leaf : leaves) {
                List<Integer> neighbors = graph.get(leaf);
                for (Integer neighbor : neighbors) {
                    indegree[neighbor]--;
                    graph.get(neighbor).remove(leaf);
                    if (indegree[neighbor] == 1) 
                        newLeaf.add(neighbor);
                }
                //delete leaf from graph
                n--;
            }
            leaves = newLeaf;
        }
        
        return leaves;
    }
}

  

310. Minimum Height Trees