Trees and Spanning Trees
A tree is a connected graph with no cycles. Trees are the minimal connected graphs: remove any edge and they fall apart, add any edge and they get a cycle. File systems, organisation charts, parse trees, decision trees and network routing tables are trees, and every connected network contains one as its backbone, a spanning tree.
Equivalent definitions
For a graph with vertices, these are equivalent:
- is connected and has no cycles (the definition).
- is connected and has exactly edges.
- has no cycles and has exactly edges.
- Between any two vertices there is exactly one path.
- is connected, and removing any edge disconnects it.
- has no cycles, and adding any edge creates a cycle.
Key lemma. Every tree with at least 2 vertices has at least 2 leaves (vertices of degree 1). Proof: the endpoints of a longest path are leaves; if an endpoint had another neighbour, either it is on the path (a cycle) or the path could be extended.
Theorem. A tree with vertices has edges.
Proof by induction on . A one-vertex tree has 0 edges. For , remove a leaf and its edge; what is left is still connected and acyclic, so by induction it has edges. Adding back the leaf gives .
Spanning trees
A spanning tree of a connected graph is a subgraph that is a tree and contains every vertex of . Every connected graph has one: while there is a cycle, delete one of its edges (the graph stays connected). A BFS or DFS from any vertex also builds one, using the edges along which new vertices are discovered.
from collections import deque
def bfs_tree(adj, root):
parent = {root: None}
q = deque([root])
while q:
u = q.popleft()
for w in adj[u]:
if w not in parent:
parent[w] = u
q.append(w)
return [(p, v) for v, p in parent.items() if p is not None]
# the 3x3 grid graph
adj = {}
for r in range(3):
for c in range(3):
v = (r, c)
adj[v] = [(r + dr, c + dc) for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]
if 0 <= r + dr < 3 and 0 <= c + dc < 3]
T = bfs_tree(adj, (0, 0))
print("graph edges:", sum(len(a) for a in adj.values()) // 2, " tree edges:", len(T))
for e in T:
print(e)graph edges: 12 tree edges: 8
((0, 0), (0, 1))
((0, 0), (1, 0))
((0, 1), (0, 2))
((0, 1), (1, 1))
((1, 0), (2, 0))
((0, 2), (1, 2))
((1, 1), (2, 1))
((1, 2), (2, 2))
Minimum spanning trees
With edge weights (cable lengths, costs), a minimum spanning tree (MST) is a spanning tree of smallest total weight. Two greedy algorithms find it, and both rest on the cut property: for any split of the vertices into two groups, the lightest edge crossing the split belongs to some MST.
- Kruskal: sort edges by weight; add each edge unless it would close a cycle (checked with union-find).
- Prim: grow one tree from a start vertex, always adding the lightest edge leaving the tree.
def kruskal(n, edges):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
tree = []
for w, u, v in sorted(edges):
ru, rv = find(u), find(v)
if ru != rv:
parent[ru] = rv
tree.append((u, v, w))
return tree
cities = ["A", "B", "C", "D", "E"]
edges = [(4, 0, 1), (8, 0, 2), (2, 1, 2), (6, 1, 3), (3, 2, 3), (9, 2, 4), (5, 3, 4), (7, 0, 4)]
T = kruskal(5, edges)
print([(cities[u], cities[v], w) for u, v, w in T])
print("total weight:", sum(w for *_, w in T))[('B', 'C', 2), ('C', 'D', 3), ('A', 'B', 4), ('D', 'E', 5)]
total weight: 14
The DSA course implements both algorithms step by step: Kruskal's Algorithm, Prim's Algorithm.
Counting trees
Cayley's formula: there are different trees on labelled vertices (3 for , 16 for , 125 for ). A neat bijective proof uses Prüfer codes, which encode each tree as a sequence of vertex labels.
In software
Spanning trees are how Ethernet switches avoid loops (the Spanning Tree Protocol), how multicast routing reaches every subscriber once, and how image segmentation and clustering group pixels (single-linkage clustering is an MST with the heaviest edges removed). DOM, JSON and abstract syntax trees are rooted trees, whose edges are the parent pointers.
Exercises
Exercise 1: Edges of a forest
A forest (a graph without cycles) has 30 vertices and 4 connected components. How many edges does it have?
Answer
Solution
Each component is a tree with edges, so the total is .
Exercise 2: Degree sum of a tree
A tree has 3 vertices of degree 3, 2 of degree 2, and the rest are leaves. How many leaves are there?
Answer
Solution
Let be the number of leaves; and . The handshake lemma gives , so and .
Exercise 3: Cayley for (code)
Count the spanning trees of by brute force (choose 3 of its 6 edges and keep the acyclic choices).
Answer
Solution
3 edges on 4 vertices form a tree exactly when they connect all vertices.
from itertools import combinations
E = list(combinations(range(4), 2))
def connected(edges):
seen, stack = {0}, [0]
while stack:
u = stack.pop()
for a, b in edges:
for x, y in ((a, b), (b, a)):
if x == u and y not in seen:
seen.add(y); stack.append(y)
return len(seen) == 4
print(sum(connected(c) for c in combinations(E, 3)), 4 ** 2)16 16
Test yourself
How many edges does a tree with 100 vertices have?
- 100
- 99
- 101
- 50
What does Kruskal's algorithm do with an edge that would close a cycle?
- Adds it anyway
- Skips it
- Removes the heaviest edge of the cycle
- Stops
How many labelled trees are there on 5 vertices (Cayley)?
- 25
- 60
- 120
- 125