您的位置:首页 > 其它

Leetcode Minimum Height Trees

2016-02-22 17:49 309 查看
Leetcode Minimum Height Trees ,本问题的关键在于理解如何找出最小高度。只要找出图中的边界点之间的最大长度n,则可以知道树的最小高度应为:(n + 1) / 2。至于图中有几个最点,其在于n为奇数或者为偶数,若n为偶数,则只有一个最小点;若n为奇数,则有两个最小点。

相关代码以及测试如下:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<queue>
#include<map>

/**
* We start the search at the leaf, because the the half of the longest distance
* between two node must be the minimum height of the tree.
*/
using namespace std;
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
vector<int> re;
// for the case that there is one element.
if (n == 1) {
re.push_back(0);
return re;
}
// Recorde the adjacent edges of a node.
vector<vector<int> > flags(n, vector<int>());
// Count the adjacent edges number of a node.
vector<int> count(n, 0);
// Mark the status of the element.
vector<bool> visited(n, false);
// Record the height of a node.
vector<int> height(n, 0);
// The leaf node.
queue<int> leaf;

// Scan the adjacent of each node.
for (auto ele: edges) {
count[ele.first] ++;
flags[ele.first].push_back(ele.second);
count[ele.second] ++;
flags[ele.second].push_back(ele.first);
}

// Get all the initial leaf
for (int i = 0; i < n; i ++) {
if (count[i] == 1) {
leaf.push(i);
}
}

int tmp;
int last = -1;
int pre_height = 0;
while (!leaf.empty() && last == -1) {
// Get a leaf.
tmp = leaf.front();
// Mark it is visited.
visited[tmp] = true;
leaf.pop();
// Scan it's ajacent node.
for (auto ele: flags[tmp]) {
pre_height = -1;
// If node visited.
if (!visited[ele]) {
// Get the greater height.
if (height[tmp] >= height[ele]) {
pre_height = height[ele];
height[ele] = height[tmp] + 1;
}
count[ele] --;
if (count[ele] == 1) {
leaf.push(ele);
} else if (count[ele] == 0) {
// The last element.
last = ele;
break;
}
}
}
}
re.push_back(last);
if (pre_height + 1 == height[last]) {
re.push_back(tmp);
}
return re;
}
};

// Sample input: ./a.out num edge1a edg1b edge2a edge3b ...
int main(int argc, char* argv[]) {
Solution so;
vector<pair<int, int>> test;
pair<int, int> tmp;
for (int i = 1; i < argc / 2; i ++) {
tmp = make_pair(atoi(argv[i * 2]), atoi(argv[i * 2 + 1]));
test.push_back(tmp);
}
vector<int> re = so.findMinHeightTrees(atoi(argv[1]), test);
cout<<"re: ";
for (auto s: re) {
cout<<s<<" ";
}
cout<<endl;
return 0;
}


测试:

./a.out 4 1 0 1 2 1 3

re: 1

./a.out 6 0 3 1 3 2 3 4 3 5 4

re: 4 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode