Skip to content

Commit a899632

Browse files
authored
Create Tree to Prufer code.cpp
1 parent 13ccca1 commit a899632

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Tree to Prufer code.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Tree to Prufer Code
3+
Complexity: O(VlogV)
4+
*/
5+
6+
vector<int> treeToPrufercode (int nodes, vector<pair<int,int>> &edges) {
7+
unordered_set<int> neighbors[nodes+1]; // For each node, who is it's neighbor?
8+
9+
for( int i = 0; i < edges.size(); i++ ) {
10+
pair<int,int> edge = edges[i];
11+
int u = edges[i].first; int v = edges[i].second;
12+
neighbors[u].insert(v);
13+
neighbors[v].insert(u);
14+
}
15+
16+
priority_queue<int> leaves;
17+
for ( int i = 0; i <= nodes; i++ ) {
18+
if (neighbors[i].size() == 1 ) {
19+
leaves.push(-i); // Negating since we need min heap
20+
}
21+
}
22+
vector<int> pruferCode;
23+
int need = nodes - 2;
24+
while(need--) {
25+
int leaf = -leaves.top(); leaves.pop();
26+
int neighborOfLeaf = *(neighbors[leaf].begin());
27+
pruferCode.push_back(neighborOfLeaf);
28+
// Remove the leaf
29+
neighbors[neighborOfLeaf].erase(leaf);
30+
// The neighbor can become a new leaf
31+
if(neighbors[neighborOfLeaf].size() == 1) {
32+
leaves.push(-neighborOfLeaf);
33+
}
34+
}
35+
return pruferCode;
36+
}

0 commit comments

Comments
 (0)