LeetCode-310. Minimum Height Trees [C++][Java]

LeetCode-310. Minimum Height Treesicon-default.png?t=M1L8https://leetcode.com/problems/minimum-height-trees/

题目描述

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.

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs).

Return a list of all MHTs' root labels. You can return the answer in any order.

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

Example 1:

Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.

Example 2:

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

Constraints:

  • 1 <= n <= 2 * 104
  • edges.length == n - 1
  • 0 <= ai, bi < n
  • ai != bi
  • All the pairs (ai, bi) are distinct.
  • The given input is guaranteed to be a tree and there will be no repeated edges.

解题思路

【C++】

BFS

1. remove leafs one by one

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
        if (n == 1) {return {0};}
        vector<unordered_set<int>> g(n);
        for (int i=0; i<edges.size(); i++) {
            g[edges[i][0]].insert(edges[i][1]);
            g[edges[i][1]].insert(edges[i][0]);
        }
        queue<int> q;
        for (int i=0; i<n; i++) {
            if (g[i].size() == 1) {q.push(i);}
        }
        while (n > 2) {
            int s = q.size();
            n = n - s;
            while (s--) {
                int j = q.front(); q.pop();
                int i = *g[j].begin();
                g[i].erase(j);
                if (g[i].size() == 1) {q.push(i);}
            }
        }
        vector<int> res;
        while (!q.empty()){
            res.push_back(q.front());
            q.pop();
        }
        return res;
    }
};

2. Topological Sort —— kHan算法

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
        if (n == 1) {return {0};}
        vector<int> graph[n];
        vector<int> in(n,0);
        for(auto k : edges){
            graph[k[0]].push_back(k[1]);
            graph[k[1]].push_back(k[0]);
            in[k[0]]++;
            in[k[1]]++;
        }
        queue<int>q;
        for (int i=0;i<n;i++) {
            if (in[i]==1) {
                q.push(i);
                in[i]--;
            }
        }
        vector<int>ans;
        while (!q.empty()){
            ans.clear();
            int s = q.size();
            while (s--) {
                int node = q.front(); q.pop();
                ans.push_back(node);
                for (auto k : graph[node]) {
                    in[k]--;
                    if (in[k] == 1) {q.push(k);}
                }
            }
        }
        return ans;
    }
};

【Java】

class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<Integer>();
        if (n==1) {
            res.add(0);
            return res;
        }
        HashMap<Integer, List<Integer>> map = new HashMap();
        int[] rank = new int[n];
        for (int i=0; i<n; i++) {map.putIfAbsent(i, new ArrayList<>());}
        for( int[] e: edges) {
            map.get(e[0]).add(e[1]);
            map.get(e[1]).add(e[0]);
            rank[e[0]]++;
            rank[e[1]]++;
        }
        Queue<Integer> q= new LinkedList();
        for (int i=0; i<n; i++) {if(rank[i]==1) {q.add(i);}}
        while (n > 2) {
            int size=q.size();
            n -= size;
            for (int i=0; i<size; i++) {
                int node = q.poll();
                for( int j: map.get(node)) {
                    rank[j]--;
                    if(rank[j]==1) {q.add(j);}
                } 
            }
        }
        res.addAll(q);
        return res; 
    }
}

参考文献

【1】m数据结构 day16 图(六)拓扑排序:为有向无环图构造拓扑序列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值