Sub topic 2
Spanning Trees: Connecting Every Vertex with V-1 Edges
This chapter assumes you know basic graph terms (vertex, edge, path, cycle), can read adjacency lists and edge lists, and can follow short Python programs. It sets weights aside and studies the structure that every minimum spanning tree has to have. Weights come back at the end of the chapter, to show why we need a better method than trying every tree.
What a spanning tree is
A tree is a connected, undirected graph with no cycles. A subgraph of a graph G uses some of G's vertices and some of G's edges. A spanning subgraph keeps every vertex of G.
A spanning tree of a connected undirected graph G = (V, E) is a spanning subgraph that is also a tree. It contains every vertex of G and a subset of G's edges, it is connected, and it has no cycles.
Every connected graph has at least one spanning tree. A disconnected graph has none, because no subset of its edges can join vertices that the full edge set cannot reach. For disconnected inputs we compute a spanning forest instead, which a later chapter covers.
Here is the running example used throughout the tutorial: four vertices and five weighted edges. One spanning tree is drawn with solid lines. The two edges it leaves out are dotted.
Why a tree on V vertices has exactly V-1 edges
Claim: every tree with n ≥ 1 vertices has exactly n − 1 edges.
The proof uses leaves. A leaf is a vertex of degree 1. Every tree with at least two vertices has at least two leaves. To see this, take a longest simple path in the tree. If one of its endpoints had a second neighbour off the path, either the path could be extended or a cycle would exist, and neither is allowed.
The induction then goes like this:
- A tree with one vertex has 0 edges, and 0 = 1 − 1.
- Take a tree with n ≥ 2 vertices. Remove one leaf and its single edge. What remains is still connected, because no path between two other vertices passed through the leaf. It still has no cycles. So it is a tree with n − 1 vertices, and by induction it has n − 2 edges.
- Put the leaf back. The tree now has n − 1 edges.
The count works from both directions:
- Fewer than V − 1 edges cannot connect V vertices. Each edge you add lowers the number of connected components by at most one. You start with V components and need to reach 1, so you need at least V − 1 edges.
- More than V − 1 edges on V vertices must contain a cycle. If there were no cycle, each component would be a tree, and the components together would have V minus (number of components) edges, which is at most V − 1.
Equivalent definitions
For a graph T with V vertices, the following statements are all equivalent. If any one holds, all of them hold.
| # | Condition on T | What it is useful for |
|---|---|---|
| 1 | Connected and acyclic | The standard definition |
| 2 | Connected with exactly V − 1 edges | Checking a tree with one traversal and one count |
| 3 | Acyclic with exactly V − 1 edges | The stopping rule in Kruskal's algorithm |
| 4 | Exactly one simple path between every pair of vertices | Reasoning about the path between two endpoints |
| 5 | Connected, but removing any edge disconnects it | Thinking of a tree as "minimally connected" |
| 6 | Acyclic, but adding any new edge creates a cycle | Thinking of a tree as "maximally acyclic" |
You will use conditions 2 and 3 most often. A greedy MST algorithm that never creates a cycle can stop once it has accepted V − 1 edges, because by condition 3 it then has a spanning tree.
Two structural facts that drive MST correctness
These two facts are what the later cut-property and cycle-property chapters build on.
Adding a non-tree edge creates exactly one cycle. Suppose edge (u, v) is in G but not in the spanning tree T. By condition 4, T already contains exactly one path from u to v. Adding (u, v) closes that path into a cycle, called the fundamental cycle of (u, v). In the diagram, adding 2-3 creates the cycle 2-1-3-2.
Removing a tree edge splits the tree into exactly two pieces. Removing edge (u, v) from T leaves two components, one containing u and one containing v. This partition of the vertices is called the fundamental cut of that edge. Any edge of G that crosses this cut can reconnect the two pieces and give a new spanning tree.
Together these facts give the exchange operation: add a non-tree edge e, then remove any other edge f on the cycle that e created. The result is another spanning tree. MST proofs use this operation repeatedly. If swapping makes the total weight smaller, the tree you started with was not minimum.
Checking whether an edge set is a spanning tree
The checker below applies condition 2. It makes sure every chosen edge exists in the graph, that there are no duplicates, that the count is n − 1, and that a breadth-first search from vertex 0 reaches every vertex.
from collections import deque
def is_spanning_tree(n, graph_edges, tree_edges):
# graph_edges, tree_edges: lists of (u, v) pairs, vertices 0..n-1
if n == 0:
return len(tree_edges) == 0
graph = {frozenset((u, v)) for u, v in graph_edges}
chosen = [frozenset((u, v)) for u, v in tree_edges]
if any(len(e) != 2 or e not in graph for e in chosen):
return False # self-loop, or edge not in the graph
if len(set(chosen)) != len(chosen) or len(chosen) != n - 1:
return False # duplicate edge, or wrong count
adj = [[] for _ in range(n)]
for u, v in tree_edges:
adj[u].append(v)
adj[v].append(u)
seen = [False] * n
seen[0] = True
reached = 1
queue = deque([0])
while queue:
x = queue.popleft()
for y in adj[x]:
if not seen[y]:
seen[y] = True
reached += 1
queue.append(y)
return reached == n
graph = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]
print(is_spanning_tree(4, graph, [(0, 1), (1, 3), (1, 2)])) # True
print(is_spanning_tree(4, graph, [(0, 1), (0, 2), (1, 2)])) # False: cycle, 3 unreachedThe edges are stored as frozenset because the graph is undirected, so (1, 2) and (2, 1) must count as the same edge. A frozenset of size 1 means a self-loop, which can never be part of a tree.
Building some spanning tree is easy
Any graph traversal gives you a spanning tree. Each time a breadth-first search (BFS) or depth-first search (DFS) discovers a new vertex, record the edge that led to it. Every vertex except the start is discovered exactly once, so you record exactly V − 1 edges, and they connect everything back to the start.
from collections import deque
def bfs_spanning_tree(adj, start=0):
# adj[v] is a list of (neighbor, weight) pairs; weights are ignored
n = len(adj)
seen = [False] * n
seen[start] = True
tree = []
queue = deque([start])
while queue:
x = queue.popleft()
for y, w in adj[x]:
if not seen[y]:
seen[y] = True
tree.append((x, y, w))
queue.append(y)
return tree
edges = [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3)]
n = 4
adj = [[] for _ in range(n)]
for w, u, v in edges:
adj[u].append((v, w))
adj[v].append((u, w))
tree = bfs_spanning_tree(adj)
print(tree) # [(0, 1, 1), (0, 2, 4), (1, 3, 2)]
print(sum(w for _, _, w in tree)) # 7This tree is valid but has total weight 7. The tree in the diagram has weight 6. BFS ignores weights, so the tree it returns depends only on adjacency order. Finding the cheapest tree needs an algorithm that pays attention to weights.
How many spanning trees are there?
The obvious way to find the cheapest tree is to list them all. The example graph has 10 sets of three edges, and you can check each one:
from itertools import combinations
pairs = [(u, v) for _, u, v in edges]
weights = []
for combo in combinations(edges, n - 1):
if is_spanning_tree(n, pairs, [(u, v) for _, u, v in combo]):
weights.append(sum(w for w, _, _ in combo))
print(len(weights)) # 8
print(sorted(weights)) # [6, 7, 8, 9, 9, 10, 11, 12]Two of the triples fail because they are the triangles 0-1-2 and 1-2-3. That leaves eight spanning trees, with weights from 6 to 12.
This approach does not scale. Cayley's formula says the complete graph on n vertices has n^(n−2) spanning trees.
| Vertices n | Spanning trees of the complete graph |
|---|---|
| 4 | 16 |
| 10 | 100,000,000 |
| 20 | about 2.6 × 10^23 |
Even sparse graphs usually have exponentially many spanning trees. That is why the rest of this tutorial uses structural properties to build the minimum tree directly, in near-linear time.
Common mistakes
- Using the definition on directed graphs. Spanning trees as defined here are for undirected graphs. The directed version, the arborescence, needs a different algorithm (Chu–Liu/Edmonds).
- Using only a count or only a connectivity check. Each one alone is not enough. Use one of the paired conditions from the table.
- Mishandling parallel edges. In a multigraph, two parallel edges between u and v form a cycle of length 2. A tree can contain at most one of them.
- Expecting a spanning tree of a disconnected graph. None exists. Check connectivity first, or compute a forest.
- Assuming the spanning tree is unique. Most graphs have many. Uniqueness comes up again for minimum spanning trees.
Exercise
A connected graph has 12 vertices and 30 edges. How many edges does each of its spanning trees contain, and how many edges of the graph are left out of any given spanning tree?
Show answer
Every spanning tree has V − 1 = 11 edges, so 30 − 11 = 19 edges are left out. Each left-out edge creates exactly one fundamental cycle when you add it back to the tree.
Exercise
In the example graph, start from the spanning tree {0-1, 1-3, 1-2}. Add the non-tree edge 0-2. Which cycle forms, which edges could you remove to get a new spanning tree, and what are the resulting weights?
Show answer
Adding 0-2 forms the cycle 0-1-2-0. You can remove 0-1, giving {0-2, 1-3, 1-2} with weight 4+2+3 = 9, or remove 1-2, giving {0-1, 1-3, 0-2} with weight 1+2+4 = 7. Removing 0-2 itself takes you back to the original tree of weight 6. No swap lowers the weight.
Exercise
Someone proposes checking for a spanning tree with "the edge set has V − 1 edges and every vertex has degree at least 1." Give a counterexample on 4 vertices.
Show answer
For 4 vertices you need 3 edges. Any 3 edges that touch all four vertices form either a path or a star, and both are trees, so there is no counterexample on 4 vertices. The rule first fails at 5 vertices: the triangle 0-1-2 has 3 edges, the edge 3-4 has 1, so there are 4 = V − 1 edges and every degree is at least 1, but the graph has a cycle and is disconnected. On 4 vertices you can still see why the degree rule is weak: with V − 1 edges, the triangle 0-1-2 leaves vertex 3 with degree 0, and a pure count does not catch that.
Exercise
Why does a BFS from any start vertex of a connected graph always produce exactly V − 1 tree edges?
Show answer
BFS records an edge only when it discovers a vertex for the first time. Every vertex except the start is discovered exactly once, because the graph is connected and the seen array blocks rediscovery. That gives V − 1 edges. The edges cannot form a cycle, because each one leads to a vertex that had no tree edge before.