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]
题目描述:
给出一个无环无向图,如果选择图中的一个顶点作为root节点,那么这个图就可以变成一棵树。题目要求我们找出使得树的高度最低的root节点的集合。
解题思路:
对于一个无环无向图,要找到其中使得树高度最低的root节点,可以想象成是从一个图的边缘顶点(度为1的顶点)一直往图的里面寻找的过程。类似地,对于一个圆,到圆的边界任何一点最近的点就是圆心。所以这里对于一个图,我们的目标就是找到一个类似圆心的顶点,就是使得树高度最低的root节点。
这个过程首先从图的所有边缘点同时开始出发,并删掉这些边缘点,之后图中会出现一些新的边缘点,直到图中剩下的点的个数不超过2。题目的给出的例子比较简单,下面我以自己设定的例子来解析这个过程。
上图中红色点表示当前的边缘点,每次找到边缘点之后去掉再继续找边缘点,最后图中只剩下顶点1和顶点4,此时不管用顶点1还是顶点4作为树的root节点,得到的树的高度都是最小的。分别以顶点1和顶点4为root节点的树结构如下图所示,可以看到两棵树的高度都为4。
代码:
//
// main.cpp
// 310. Minimum Height Trees
//
// Created by mingjc on 2017/4/2.
// Copyright © 2017年 mingjc. All rights reserved.
//
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
vector<unordered_set<int>> adjList(n);
unordered_set<int> vSet;
for (int i = 0; i < n; i++) {
vSet.insert(i);
}
for (int i = 0; i < edges.size(); i++) {
adjList[edges[i].first].insert(edges[i].second);
adjList[edges[i].second].insert(edges[i].first);
}
while (vSet.size() > 2) {
vector<int> temp;
for (int i = 0; i < adjList.size(); i++) {
if (adjList[i].size() == 1) { //判断是否叶子结点
temp.push_back(i);
temp.push_back(*adjList[i].begin());
}
}
for(int i = 0; i < temp.size(); i+=2) {
int adj0 = temp[i];
int adj1 = temp[i + 1];
adjList[adj0].erase(adj1);
adjList[adj1].erase(adj0);
vSet.erase(adj0);
// cout << "erase " << adj0 << endl;
}
}
vector<int> result(vSet.begin(), vSet.end());
return result;
}
};
int main(int argc, const char * argv[]) {
vector<pair<int, int>> edges;
edges.push_back(make_pair<int, int>(3, 0));
edges.push_back(make_pair<int, int>(3, 1));
edges.push_back(make_pair<int, int>(3, 2));
edges.push_back(make_pair<int, int>(3, 4));
edges.push_back(make_pair<int, int>(5, 4));
Solution sln;
vector<int> result = sln.findMinHeightTrees(6, edges);
return 0;
}