Middle-题目85:310. Minimum Height Trees

原创 2016年05月31日 17:17:56

题目原文:
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]
题目大意:
给出一个树,它的任何一个顶点都可以看做树的根节点,写一个函数,输出使得树高度最小的顶点的列表。
输入参数是顶点个数和边的列表(用二维数组表示)。
例如,输入n = 4, 边列表= [[1, 0], [1, 2], [1, 3]]
则以1为根节点的树的高度最小。
题目分析:
不管树有多复杂,使得高度最小的顶点至多有2个。(我也想不出证明过程……)
暴力解法是对每个节点求高度。这里有一个比较好的算法,即每轮去掉度为1的节点,直到顶点剩下1个或2个(显然不可能是3个或更多,因为没有环),那么这1个或2个节点即为所求。
源码:(language:java)

public class Solution {    
    public  List<Integer> findMinHeightTrees(int n, int[][] edges) {
        Map<Integer, Set<Integer>> adjList = new HashMap<Integer,Set<Integer>>();
        boolean[] isLeaf = new boolean[n];
        int[] degrees = new int[n];
        int nextVertical = 0, currentVerticals = n;
        for(int i = 0; i<n;i++)
            adjList.put(i, new HashSet<Integer>());
        for(int[] edge : edges) {
            adjList.get(edge[0]).add(edge[1]);
            degrees[edge[0]]++;
            adjList.get(edge[1]).add(edge[0]);
            degrees[edge[1]]++;
        }
        while(currentVerticals > 2) {
            for(int i = 0;i<n;i++) {
                if(degrees[i]==1) {
                    isLeaf[i] = true;
                }
            }
            for(int i = 0;i<n;i++) {
                if(isLeaf[i]) {
                    nextVertical = adjList.get(i).iterator().next();
                    degrees[i]--;
                    degrees[nextVertical]--;
                    adjList.get(i).remove(nextVertical);
                    if(degrees[i]==0)
                        currentVerticals--;
                    adjList.get(nextVertical).remove(i);
                    if(degrees[nextVertical]==0)
                        currentVerticals--;
                    isLeaf[i] = false;
                }
            }
        }
        List<Integer> list = new ArrayList<Integer>();
        for(Integer key : adjList.keySet()) {
            if(adjList.get(key).size()!=0)
                list.add(key);
        }
        if(n==1)
            list.add(0);
        if(currentVerticals==0)
            list.add(nextVertical);
        return list;
    }
}

这里给出discuss中一位大神给出的算法,思路是一样的,但省略了很多循环:

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        if (n == 1) 
            return Collections.singletonList(0);
        List<Set<Integer>> adj = new ArrayList<>(n);
        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]);
        }

        List<Integer> leaves = new ArrayList<>();
        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) {
                int j = adj.get(i).iterator().next();
                adj.get(j).remove(i);
                if (adj.get(j).size() == 1) newLeaves.add(j);
            }
            leaves = newLeaves;
        }
        return leaves;
    }
}

成绩:
算法一(我写的):170ms,beats 14.07%,众数56ms,5.12%
算法二(from discuss):58ms,beats 68.02%
Cmershen的碎碎念:
这是leetcode里面第一个涉及图的题,图应该是数据结构里面的难点,因此这题的成绩很分散。同时说明,即使算法思路相同,内部实现细节不同也会导致成绩有很大差异。比如记录邻接表的时候人家用的是list的下标而不是使用Map的key值,而一直用leaves数组维护当前叶子节点而不是一直在数度,也是比较巧妙的。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

LeetCode 310 Minimum Height Trees

题目For a undirected graph with tree characteristics, we can choose any node as the root. The result g...

Leetcode: 310.Minimum Height Trees

Leetcode: 310.Minimum Height Trees

【LEETCODE】310-Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result gra...

[leetcode] 310.Minimum Height Trees

leetcode 310.Minimum Height Trees

leetcode 310. Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result gra...

leetcode 310. Minimum Height Trees 解题报告

原题链接原题链接解题思路常规方法可以使用BFS或者DFS,对每个点都遍历一遍,求出所有点组成的树的高度,然后找出哪些高度最小的节点,可以通过不断更新最低高度来进行剪枝。但是时间复杂度过高。 最终的解...
  • jly0612
  • jly0612
  • 2016年09月04日 17:08
  • 351

310. Minimum Height Trees (无向图中,找最小高度的根)

对比题目,找最大高度根 PAT 1021. Deepest Root (25) http://blog.csdn.net/qq_26437925/article/details/493297633...

算法分析与设计第三周习题:图论算法之310. Minimum Height Trees

今天刚上完算法课,课上知识内容包括拓扑排序和图论一些基本知识,所以我就去leetcode上面找了一道有关图论的题目来巩固自己所学的知识。题目简介: For a undirected graph wi...

【Leetcode】310. Minimum Height Trees

Description:For a undirected graph with tree characteristics, we can choose any node as the root. Th...

LeetCode-310. Minimum Height Trees (JAVA) 图中最矮的树

LeetCode-310. Minimum Height Trees (JAVA) 图中最矮的树
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目85:310. Minimum Height Trees
举报原因:
原因补充:

(最多只允许输入30个字)