Prufer Codes

Consider an n-vertex tree which has its vertices labelled as 0, 1, 2, ..., n-1. The Prufer code for this tree can be computed as follows:
Repeat n-2 times:

  1. Find the leaf with the smallest label u where (u, v) is the edge in the tree which is incident to vertex u.
  2. Append v to the Prufer code.
  3. Delete u and the edge (u, v) from the tree.

The sequence of n-2 numbers produced is the Prufer code for the labelled tree.


Given a sequence of n-2 integers in the range 0, 1, ..., n-1, the tree which corresponds to this Prufer code can be reconstructed by the following algorithm:

Set used[i] = false for i= 0, 1, ..., n-1.

Set count[i] to be the number of occurrences of i in the Prufer code sequence.

While the Prufer code is not empty do:

  1. Let x be the unused vertex having count[u]=0 that has minimum label.
  2. Set used[x]= true.
  3. Add edge (x, s) to the tree where s is the first integer in the Prufer code sequence.
  4. Set count[s]= count[s]-1.
  5. Remove the first integer of the Prufer code from the sequence.
When this is done, two vertices say u and v are still unused. Add edge (u, v) to the tree.