Advanced 12 min

Minimum spanning trees

A minimum spanning tree connects every vertex in a weighted undirected graph with the smallest possible total cost.

How it works

In the triangle, start with all vertices separate. Taking AB joins two groups; taking BC places all three together. When AC arrives, A and C already share a group, so adding that edge would close a loop. Sorting edges and detecting these loops are the two jobs in Kruskal’s method.

Walk through an example

Kruskal’s algorithm considers edges by increasing weight. Add an edge if it joins two different groups, then merge the groups with union-find.

What to watch for

An individual cheapest route between two vertices is a different goal. In a disconnected graph, the algorithm produces a forest instead of a single tree.

Code example

def kruskal(n, edges):
    parent = list(range(n))
    def find(x):
        while x != parent[x]:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    chosen = []
    for a, b, weight in sorted(edges, key=lambda edge: edge[2]):
        left, right = find(a), find(b)
        if left != right:
            parent[right] = left
            chosen.append((a, b, weight))
    return chosen

Check your understanding

What is the cost of the minimum spanning tree?

See the example and explanation
Worked example
Given Triangle edges AB = 1, BC = 2, AC = 5
Answer 3

Take AB and BC. They connect all three vertices at total cost 3, so AC would only add a cycle.

Open practice problem
Next lessonBellman–Ford and negative edges