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<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        
        vector<vector<int> > adj(n);
        vector<int> degree(n),res;
        if(n==1)
        {
            res.push_back(0);
            return res;
        }
        queue<int> que;
        int count=0;
        int now=0,next=0;//这一层和下一层结点数
        for(int i=0;i<edges.size();i++)
        {
            adj[edges[i].first].push_back(edges[i].second);
            adj[edges[i].second].push_back(edges[i].first);
            degree[edges[i].first]++;
            degree[edges[i].second]++;
        }
        for(int i=0;i<n;i++)
        {
            if(degree[i]==1)
            {
                que.push(i);
                now++;
            }
        }
        while(!que.empty()&&count<n-2)
        {
            int cur=que.front();que.pop();
            count++;
            for(int i=0;i<adj[cur].size();i++)
            {
                degree[adj[cur][i]]--;
                if(degree[adj[cur][i]]==1)
                {
                    que.push(adj[cur][i]);
                    next++;
                }
            }
            now--;
            if(now==0)//一层结束
            {
                now=next;next=0;
            }
        }
        if(next==0)//剩下的两个点都是
        {
            res.push_back(que.front());
        }
        que.pop();
        res.push_back(que.front());
        return res;

}
    
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值