Minimum Height Trees Solutions in C++
Number 310
Difficulty Medium
Acceptance 32.3%
Link LeetCode
Other languages —
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/minimum-height-trees/// Author : Hao Chen// Date : 2016-01-24class Solution {public:vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {//corner caseif ( n <= 1 ) return {0};//construct a edges search data stucturevector<unordered_set<int>> graph(n);for (auto e : edges) {graph[e.first].insert(e.second);graph[e.second].insert(e.first);}//find all of leaf nodesvector<int> current;for (int i=0; i<graph.size(); i++){if (graph[i].size() == 1) current.push_back(i);}// BFS the graphwhile (true) {vector<int> next;for (int node : current) {for (int neighbor : graph[node]) {graph[neighbor].erase(node);if (graph[neighbor].size() == 1) next.push_back(neighbor);}}if (next.empty()) break;current = next;}return current;}};