Guest User
Using app without sign in

Practice book
Graph Theory Through Problems300 Exercises with Hints, Worked Algorithms and Complete Solutions
By Mohammed Islam Hadjoudj
Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.
Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on AmazonSelect an algorithm and generate steps to begin visualization
One labeled tree, one sequence of n - 2 labels
algorithms.prufercode.description
Select an algorithm and generate steps to begin visualization
A Prüfer code, or Prüfer sequence, is a list of n - 2 vertex labels that describes a labeled tree on n vertices exactly. Every labeled tree has one code, and every list of n - 2 labels is the code of exactly one tree. Heinz Prüfer introduced it in 1918 to prove Cayley's formula, which says there are n^(n-2) labeled trees on n vertices.
To encode, remove the leaf with the smallest label and write down its neighbour, and repeat until only two vertices are left. To decode, give each vertex the degree 1 plus the number of times it appears in the code. Then, for each label a of the code in order, join a to the smallest vertex whose degree is 1 and lower both degrees by one. When the code is used up, join the last two vertices of degree 1. Since a vertex's degree in the tree is one more than its number of appearances in the code, the leaves are exactly the labels the code never mentions. With a priority queue of leaves both directions take O(n log n) time.
Prüfer codes turn trees into plain sequences. That makes them the standard way to generate uniformly random labeled trees, a compact way to store and compare trees, and a common encoding in genetic algorithms that search over spanning trees, where a sequence is easier to mutate and recombine than a tree. In combinatorics courses they are the classic bijective proof of Cayley's formula, and they also count the trees with prescribed vertex degrees.
Read the full article: Trees in Graph Theory
Read the full article: Degree of a Vertex and the Handshaking Lemma
Related algorithms: algorithms.havelhakimi.name, Prim's MST Algorithm, Kruskal's MST Algorithm, Depth-First Search