leetcode-310. Minimum Height Trees

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 = 4edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3

return [1]

Example 2:

Given n = 6edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
      \ | /
        3
        |
        4
        |
        5

return [3, 4]

Hint:

  1. How many MHTs can a graph have at most?

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.

题意解析:

题目大概就是告诉你有一个无向图。你可以选取其中一个节点作为根节点来生成树。现在要求生成的树的高度最小,给出最小高度树的根节点。

看到这道题,首先想到的应该是遍历每个节点,看看谁当根高度最小。当然这是不可能的,因为复杂度想想就很高,所以我们反过来,从叶子入手。每次去掉一圈叶子节点,最后剩下的当根就是高度最小树。这个答案不是1个就是2个,可以试着画图看看,代码如下:

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> leaves = new LinkedList();
        if(n == 0){
            return leaves;
        }
        if(n == 1){
            leaves.add(0);
            return leaves;
        }
        HashSet<Integer>[] graph = new HashSet[n];
        for(int i = 0; i < n; i++){
            graph[i] = new HashSet();
        }
        
        for(int x[] : edges){
            graph[x[0]].add(x[1]);
            graph[x[1]].add(x[0]);
        }
        
        for(int i = 0; i < n; i++){
            if(graph[i].size() == 1){
                leaves.add(i);
            }
        }
        
        while(n > 2){
            List<Integer> newLeaves = new LinkedList();
            for(int x : leaves){
                for(int y : graph[x]){
                    graph[x].remove(y);
                    graph[y].remove(x);
                    n--;
                    if(graph[y].size() == 1){
                        newLeaves.add(y);
                    }
                }
            }
            leaves = newLeaves;
        }
        return leaves;
    }
}

这里要注意一下。使用LinkedList比ArrayList快,因为LinkedList插入快读取慢,而ArrayList正好相反,这道题更适合使用LinkedList

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章