- Minimum Height Trees My Submissions QuestionEditorial Solution
Total Accepted: 12164 Total Submissions: 45386 Difficulty: Medium
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]
题意:
对于一棵无向树,我们可以选择它的任意节点作为根。得到的结果就是有根树。在所有可能的有根树中,高度最小的称为最小高度树(MHT)。给定一个无向图,编写函数找出所有的最小高度树,并返回其根标号的列表。
思路:逐步去掉相应的叶子节点,那么最后剩下的便是根节点(<=2)
如上图:1.去掉0,1,2,再去掉5
算法如下:
注意:尽量节省时间,否则很容易就time limited!!!!
以下的新一轮叶子节点尽量一次得到,不要再另外扫描,否则超时
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
int nsize=edges.size();
set<int> ps;
map<int,set<int>> mp; //类似于邻接表
for(int i=0;i<nsize;++i){
mp[edges[i].first].insert(edges[i].second);
mp[edges[i].second].insert(edges[i].first);
}
set<int> leaf;
auto it = mp.begin();
while(it!=mp.end()){
if(it->second.size()==1)leaf.insert(it->first); //第一次得到叶子节点集合
++it;
}
while(mp.size()>2){ //当剩下的节点数>2
set<int> newleaf;
auto it2 = mp.begin();
while(it2!=mp.end()){
if(leaf.count(it2->first)){ //如果当前节点在叶子节点
auto itbeg = (it2->second).begin();
auto itend = (it2->second).end();
while(itbeg!=itend){ //使得和叶子节点相邻的节点不再和叶子节点相连
mp[*itbeg].erase(it2->first);
if(mp[*itbeg].size()==1)newleaf.insert(*itbeg); //加入到新一轮的叶子节点
++itbeg;
}
auto it2next = ++it2; //确保迭代器有效
--it2;
mp.erase(it2); //删除叶子节点
it2 = it2next;
}
else ++it2;
}
leaf = newleaf; //更新新一轮的叶子节点
}
vector<int> res;
if(n==1){ //如果n==1要求直接返回0
res.push_back(0);
return res;
}
auto mit=mp.begin();
while(mit!=mp.end()){
res.push_back(mit->first);
++mit;
}
return res;
}
};