第三周 Minimum Height Trees

Course Schedule II

操作不当重写了这篇。。

这一周是图的问题
LeetCode上的310题:Minimum Height Trees

题目

对于一个无向无环图,可以选取一个节点作为根,这个图可以看作以该节点为根的树,找出其中高度最低的树的根(可能不止一个)

Example1:

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]

题解

可以用暴力方式对每个节点进行一次DFS算法找到树的节点,但用时太长,这里用的方法是找到图中所有度为1的节点,删除这些节点和这些节点的边,继续找下一批度为1的节点,循环直到节点都被删除,最后一批删除的节点就是所求。

代码

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        if (n == 1) return vector<int>{0};

        vector<list<int>> adjacency_list(n);
        vector<int> degree(n);
        list<int> _list;
        vector<int> result;

        for (auto edge : edges) {
            adjacency_list[edge.first].push_back(edge.second);
            adjacency_list[edge.second].push_back(edge.first);
            degree[edge.first]++;
            degree[edge.second]++;
        }

        for (int i = 0; i < n; i++) {
            if (degree[i] == 1) {
                _list.push_back(i);
            }
        }

        while (!_list.empty()) {
            result = vector<int>(_list.begin(), _list.end());
            for (auto i : result) {
                for (auto vetrix : adjacency_list[i]) {
                    adjacency_list[vetrix].remove(i);
                    if (--degree[vetrix] == 1) _list.push_back(vetrix);
                }
                _list.pop_front();
            }
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值