[leetcode] 310. Minimum Height Trees

来源:互联网 发布:一键网络共享工具 编辑:程序博客网 时间:2024/04/30 10:02

题目:
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
原创粉丝点击