310. Minimum Height Trees
- Total Accepted: 29676
- Total Submissions: 103641
- Difficulty: Medium
- Contributor: LeetCode
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]
思路:
寻找最小高度的生成树根节点可以等价为该图最长路径的中间一个(若路径顶点数为奇数)或两个(若路径顶点数为偶数),为了确定最长路径,使用两次BFS算法,第一次从任一顶点出发,找到距离该顶点最远的叶子节点(该节点必定是最长路径的一个起始端点,因为任一顶点必定是位于最长路径上或位于它的分支,所以它所能到达的最远距离就是最长路径的端点)。第二次BFS搜索则从该叶子节点出发,由此得到的最长路径就是该图的最长路径。下面代码中,二维数组graph用于构造该图的边,数组d用于记录出发顶点到该点的距离,pre数组记录所在点对应的上一顶点。然后将最长路径保存到h1数组,返回好h2时,若h1数组容量为奇数则h2保存其位于(size / 2)的元素,若为偶数则保存(size / 2 - 1)和(size / 2)的元素。
代码:
class Solution {
public:
int sum;
vector
findMinHeightTrees(int n, vector
>& edges) {
int size = edges.size();
this->sum = n;
vector
d1(n);
vector
d2(n); vector
h1, h2; vector
> graph(n); vector
pre(n, -1); for(int i = 0; i < size; i ++){ graph[edges[i].first].push_back(edges[i].second); graph[edges[i].second].push_back(edges[i].first); } bfs(graph, 0, d1, pre); int num1 = 0; for(int i = 0; i < n; i ++){ if(d1[i] > d1[num1]) num1 = i; } bfs(graph, num1, d2, pre); int num2 = 0; for(int i = 0; i < n; i ++){ if(d2[i] > d2[num2]) num2 = i; } while(num2 != -1){ h1.push_back(num2); num2 = pre[num2]; } int s = h1.size(); if(s % 2 == 1){ h2.push_back(h1[s / 2]); } else{ h2.push_back(h1[s / 2 - 1]); h2.push_back(h1[s / 2]); } return h2; } void bfs(vector
> &graph, int k, vector
&d, vector
&pre){ vector
visited(sum, false); queue
q; q.push(k); visited[k] = true; d[k] = 0; pre[k] = -1; while(!q.empty()){ int f = q.front(); for(int i = 0; i < graph[f].size(); i ++){ if(visited[graph[f][i]] == false){ visited[graph[f][i]] = true; d[graph[f][i]] = d[f] + 1; pre[graph[f][i]] = f; q.push(graph[f][i]); } } q.pop(); } } };