Skip to content

Create 310. Minimum Height Trees #463

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions 310. Minimum Height Trees
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@

class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if(edges.size() == 0) {
vector<int> tmp;
tmp.push_back(0);
return tmp;
}
unordered_map<int, list<int>> adj;

// creating adjacency list
for (int i = 0; i < edges.size(); i++) {
int u = edges[i][0];
int v = edges[i][1];
adj[u].push_back(v);
adj[v].push_back(u);
}

vector<int> leaves; // Stores current leaf nodes

// Initialize leaves with nodes having only 1 adjacent node
for(auto& d : adj) {
if(d.second.size() == 1) {
leaves.push_back(d.first);
}
}

// answer can consist of max. 2 nodes (Reason explained above)
while(n > 2) {
vector<int> new_leaves;

// remove current leaves
n -= leaves.size();

for(int leaf : leaves) {
// get the only neighbour of leaf
int neighbor = adj[leaf].front();
// remove leaf from neighbour's adjacency list
adj[neighbor].remove(leaf);

// if the adjacent node becomes a leaf node after removal, add it to the queue.
if(adj[neighbor].size() == 1) {
new_leaves.push_back(neighbor);
}
}

// update current no of leaf nodes
leaves = new_leaves;
}

return leaves;
}
};
Loading