leetcode [310]Minimum Height Trees

For an 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 :

Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3 

Output: [1]

Example 2 :

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

     0  1  2
      \ | /
        3
        |
        4
        |
        5 

Output: [3, 4]

Note:

  • 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.”
  • The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

题目大意:

找到最小高度的树。

解法:

leetcode越做到后面越做不动了,感觉好难啊...

这道题目参考了一下网上的解法,使用adj记录无向图的连接。

然后我们从每一个端点开始,这里的端点指的是1次顶点(也就是叶节点)我们让指针以相同的速度移动。当两个指针相遇时,我们只保留其中的一个,直到最后两个指针相遇或者一步之外,我们才找到根。

实际实现类似于BFS拓扑排序。删除叶子,更新内顶点的度数。然后把新叶子去掉。逐级执行,直到剩下2或1个节点为止。剩下的答案了!

时间复杂度和空间复杂度均为O(n)。

java:

class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        if (n==1) return Collections.singletonList(0);

        List<HashSet<Integer>>adj=new ArrayList<>(n);
        for (int i=0;i<n;i++) adj.add(new HashSet<Integer>());
        for (int i=0;i<edges.length;i++){
            adj.get(edges[i][0]).add(edges[i][1]);
            adj.get(edges[i][1]).add(edges[i][0]);
        }
        List<Integer> leaves=new ArrayList<>();
        for (int i=0;i<adj.size();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;
    }
}

  

posted @ 2019-05-20 11:42  小白兔云  阅读(213)  评论(0编辑  收藏  举报