题目:
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]
Note:
(1) According to the definition of tree on Wikipedia: “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.”
(2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
题解:
/*#include <iostream>
#include<set>
#include<vector>
#include<map>
#include<list>
#include<queue>
using namespace std;*/
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
if(n==1) return vector<int>{0};
map<int,set<int> > flights;
vector<int> buffer1;
vector<int> buffer2;
vector<int>* pb1 = &buffer1;
vector<int>* pb2 = &buffer2;
for(auto& edge:edges){
flights[edge.first].insert(edge.second);
flights[edge.second].insert(edge.first);
}
for(auto& flight:flights){
if(flight.second.size() == 1)
pb2->push_back(flight.first);
}
do{
pb1->clear();
swap(pb1,pb2);
for(auto& b:*pb1){
for(auto& n:flights[b]){
flights[n].erase(b);
if(flights[n].size()==1){
pb2->push_back(n);
}
}
}
}while(!pb2->empty());
return *pb1;
}
/*
int main()
{
vector<pair<int, int>> tree0 = {{0,1}};
vector<int> result = findMinHeightTrees(1,tree0);
for(auto& num:result){
cout << num << endl;
}
return 0;
}
*/
思路:
第一次,我的想法是对每一个结点得到它的最远路长度,对于最远路长度节点得到它的最远路径,路径的中间就是所求根
然而到999个节点的案例时就超时了
第二次,我上网找了下寻找最长路径,也就是图的直径的方法,得到的算法是:对任意一个节点,寻找离他最远的节点,这个节点就是图直径的端点,再从这个端点寻找离他最远的点,就能得到另一个端点,从而得到直径路径
然而到5000个节点的案例时就超时了
第三次,我看leetcode上的discuss,vote最高的几个答案都是说:删除所有叶子,然后第二轮再删除所有新的叶子,如此循环直到点集合为空,则最近一轮的叶子就是解,原解:https://discuss.leetcode.com/topic/30535/c-solution-o-n-time-o-n-space/3
这...怎么想得出来啊,以后还是先在心里想定一个算法,再在discuss里对答案,最后才下手写代码好了,耗不起这时间