File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ class Solution {
3+ public:
4+ vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
5+ if(edges.size() == 0) {
6+ vector<int> tmp;
7+ tmp.push_back(0);
8+ return tmp;
9+ }
10+ unordered_map<int, list<int>> adj;
11+
12+ // creating adjacency list
13+ for (int i = 0; i < edges.size(); i++) {
14+ int u = edges[i][0];
15+ int v = edges[i][1];
16+ adj[u].push_back(v);
17+ adj[v].push_back(u);
18+ }
19+
20+ vector<int> leaves; // Stores current leaf nodes
21+
22+ // Initialize leaves with nodes having only 1 adjacent node
23+ for(auto& d : adj) {
24+ if(d.second.size() == 1) {
25+ leaves.push_back(d.first);
26+ }
27+ }
28+
29+ // answer can consist of max. 2 nodes (Reason explained above)
30+ while(n > 2) {
31+ vector<int> new_leaves;
32+
33+ // remove current leaves
34+ n -= leaves.size();
35+
36+ for(int leaf : leaves) {
37+ // get the only neighbour of leaf
38+ int neighbor = adj[leaf].front();
39+ // remove leaf from neighbour's adjacency list
40+ adj[neighbor].remove(leaf);
41+
42+ // if the adjacent node becomes a leaf node after removal, add it to the queue.
43+ if(adj[neighbor].size() == 1) {
44+ new_leaves.push_back(neighbor);
45+ }
46+ }
47+
48+ // update current no of leaf nodes
49+ leaves = new_leaves;
50+ }
51+
52+ return leaves;
53+ }
54+ };
You can’t perform that action at this time.
0 commit comments