[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 = 4, edges = [[1, 0], [1, 2], [1, 3]]

    0
    |
    1
   / \
  2   3

return [1]

Example 2:

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

 0  1  2
  \ | /
    3
    |
    4
    |
    5

return [3, 4]

Show Hint
题意:
给一个数字n,代表了无向图的节点总数。然后给出该图中所有的边。找出以某个节点为根节点,使得树的高度最短。
思路:
最简单的暴力的方式就是尝试以每个节点作为根节点,然后使用广度优遍历的方法去遍历这个树的高度。不过这样的话时间复杂度就变成了O(n^2)。
换一个思路。我们知道在树中有叶子节点跟非叶子节点两种。叶子节点的度是1,即只有一个点与叶子节点相邻(也或者只有一个节点的话就没有相邻的节点)。中间节点的度都>=2。
另一个知识就是去找一根绳子的长度,我们可以让两只蚂蚁从两端开始爬行,每次爬一步,若干步后它们相遇或者只差一步就说明找到了绳子的长度了。
结合上面的知识,我们使用这样的思路,让蚂蚁从各个叶子往中间爬,每次爬一步之后,丢弃上一个节点,并且判断此时哪些成为了叶子节点,然后继续爬,直到最后两个蚂蚁相遇或者差一步就是最长的一个距离了。这两个蚂蚁的位置就是根的位置,这个树最少要有这么高。

代码如下:

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
        vector<int>result;
        if(n == 0)return result;
        if(n == 1)return vector<int>(1,0);
        int min_height = INT_MAX;
        vector<unordered_set<int>> edge(n, unordered_set<int>());
        for(auto ed:edges) {
            edge[ed.first].insert(ed.second);
            edge[ed.second].insert(ed.first);
        }

        vector<int> leaves;
        for(auto i = 0; i < n; i++) {
            if(edge[i].size() == 1)leaves.push_back(i);
        }

        vector<int> newLeaves;
        while(n > 2) {
            n -= leaves.size();
            for(auto i:leaves) {
                for(auto j:edge[i]) {
                    edge[j].erase(i);
                    if(edge[j].size() == 1)newLeaves.push_back(j);
                }
            }
            leaves = newLeaves;
            newLeaves.clear();
        }
        return leaves;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值