descrption
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]]
return [1]
Example 2:
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
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.解题思路
这道题是让寻找最小高度树的根。首先有一个很暴力的想法就是使每个node都作为根,用BFS得到其对应的高度,找到其中最小的高度就得到了答案,这样算法简单但是复杂度却很高。换一个思路,我们要找最小的高度,那么最长路径的中点node就是最小高度的根,这时把问题转换到找最长路径的中点问题。当最长路径上有奇数个node时,那么中间的node就是我们要找的root,当最长路径上有偶数个node时,中间的两个node就是我们要找的root。
现在的问题又转到我们如何找到最长的路径呢?我们一步一步的将路径两端的节点删除,最后的剩下的肯定是最长路径的中点node。对于树而言,我们就是每次把度数为1的节点删掉,一层层去掉叶子结点之后剩下的一个或两个node就是最小高度树的根。代码如下
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
vector<int> ans;
unordered_map<int, unordered_set<int>> edge;
if(edges.empty()){
ans.push_back(0);
return ans;
}
for(auto node : edges){
edge[node.first].insert(node.second);
edge[node.second].insert(node.first);
}
//find leaf
queue<int> leaves;
for(int i = 0; i < n; i++){
if(edge[i].size() == 1){
leaves.push(i);
}
}
int nodeleft = n;
while(nodeleft > 2){
int len = leaves.size();
for(int j = 0 ; j < len; j++){
int leaf = leaves.front();
leaves.pop();//delete one leaf
nodeleft--;
int leaf_con = *edge[leaf].begin();
edge[leaf_con].erase(leaf);
if(edge[leaf_con].size() == 1){
leaves.push(leaf_con);
}
}
}
while(!leaves.empty()){
ans.push_back(leaves.front());
leaves.pop();
}
return ans;
}
};
原题地址
如有问题请指出,谢谢!