Minimum Spanning Tree
Connect every node of a weighted graph at the least total cost: Kruskal with Union-Find, Prim with a heap, and the tricks for points in the plane, wells, and critical edges.
Overview
A spanning tree of a connected, undirected graph is a set of edges that joins every node with no cycle. It always has exactly V - 1 edges for V nodes. When the edges have weights, the minimum spanning tree (MST) is the spanning tree with the smallest total weight: the cheapest way to wire every city, house or server together.
This page uses one graph throughout: five nodes and seven weighted edges.
Checking every spanning tree is hopeless: this small graph already has 21. Two greedy algorithms find the MST directly, and both rest on one fact.
Why greedy works
Split the nodes into any two groups (a cut). The lightest edge that crosses the cut belongs to some MST. This is the cut property. The reason: any spanning tree must cross the cut somewhere, and if it uses a heavier crossing edge, swapping in the lightest one keeps it a tree and lowers the total.
The mirror image is the cycle property: when the weights are distinct, the heaviest edge on any cycle is in no MST, because the rest of the cycle already connects its two ends.
Each algorithm in this chapter leans on one of them. Prim uses the cut property, where the cut is the tree so far versus the nodes not yet in it. Kruskal uses the cycle property: an edge that would close a cycle is skipped. Both add edges one at a time, always the cheapest edge that is still safe, and both stop after V - 1 edges.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio