1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| class Solution { public: int findFarthestNode(unordered_map<int,vector<int>> &map, unordered_map<int,int> &depth, int node, int n) { vector<int> visit(n,0); visit[node] = 1; queue<pair<int,int>> q; q.emplace(node,0); int maxDepth = 0; int farthestNode = node; while(!q.empty()) { int node = q.front().first; int h = q.front().second; q.pop(); depth[node] = h; if (h > maxDepth) { farthestNode = node; } for (int nextNode:map[node]) { if (visit[nextNode]) { continue; } visit[nextNode] = 1; q.emplace(nextNode,h+1); } } return farthestNode; } vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) { if (n == 1) { return { 0 } ; } unordered_map<int,vector<int>> map; for (auto &edge:edges) { map[edge[0]].push_back(edge[1]); map[edge[1]].push_back(edge[0]); } unordered_map<int,int> depth1; unordered_map<int,int> depth2; int node1 = findFarthestNode(map,depth1,0,n); int node2 = findFarthestNode(map,depth2,node1,n); findFarthestNode(map,depth1,node2,n); vector<int> ans; if (depth2[node2]&1) { int mid = depth2[node2]/2; for (auto &it:depth2) { if (it.second == mid && depth1[it.first] == mid+1) { ans.push_back(it.first); } if (it.second == mid+1 && depth1[it.first] == mid) { ans.push_back(it.first); } } } else { int mid = depth2[node2]/2; for (auto &it:depth2) { if (it.second == mid && it.second == depth1[it.first]) { ans.push_back(it.first); } } } return ans; } } ;
|