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]


解法:假如以图中某个点为根得到一个树,那么图中度为1的点就是根树的叶子节点。所以可以依次去掉度为1的节点,最后剩下的一个或者两个点就是最小高度树的根。注意最后一定会剩下一个或者两个点,因为度数不超过1的简单连通图只可能有一个顶点或者两个顶点。

  我用了类似拓扑排序的算法来不断去掉叶子节点的。类比拓扑排序中对入度为0的点的操作,可以设一个队列,先把度数为1的节点放入队列中。然后每次队首出队,把它的邻居节点的度数减1,如果度数减完后等于1,就把邻居节点放入队列中。

复杂度:O(|V| |E|)

代码:

class Solution {
public:
    vector findMinHeightTrees(int n, vector>& edges) {
        
        vector > adj(n);
        vector degree(n),res;
        if(n==1)
        {
            res.push_back(0);
            return res;
        }
        queue que;
        int count=0;
        int now=0,next=0;//这一层和下一层结点数
        for(int i=0;i



你可能感兴趣的:(Leetcode(310) Minimum Height Trees)