TExcelTAD
Home › Discrete Mathematics › Trees and Spanning Trees

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 TT with nn vertices, these are equivalent:

  1. TT is connected and has no cycles (the definition).
  2. TT is connected and has exactly n−1n - 1 edges.
  3. TT has no cycles and has exactly n−1n - 1 edges.
  4. Between any two vertices there is exactly one path.
  5. TT is connected, and removing any edge disconnects it.
  6. TT 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. ■\blacksquare

Theorem. A tree with nn vertices has n−1n - 1 edges.

Proof by induction on nn. A one-vertex tree has 0 edges. For n≥2n \ge 2, remove a leaf and its edge; what is left is still connected and acyclic, so by induction it has n−2n - 2 edges. Adding back the leaf gives n−1n - 1. ■\blacksquare

Spanning trees

A spanning tree of a connected graph GG is a subgraph that is a tree and contains every vertex of GG. 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.

python · try it yourself
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.
python · try it yourself
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 nn−2n^{n-2} different trees on nn labelled vertices (3 for n=3n = 3, 16 for n=4n = 4, 125 for n=5n = 5). A neat bijective proof uses Prüfer codes, which encode each tree as a sequence of n−2n - 2 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 n−1n - 1 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 ni−1n_i - 1 edges, so the total is ∑(ni−1)=30−4=26\sum (n_i - 1) = 30 - 4 = 26.

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 ℓ\ell be the number of leaves; n=5+ℓn = 5 + \ell and ∣E∣=n−1=4+ℓ\lvert E \rvert = n - 1 = 4 + \ell. The handshake lemma gives 9+4+ℓ=2(4+ℓ)9 + 4 + \ell = 2(4 + \ell), so 13+ℓ=8+2ℓ13 + \ell = 8 + 2\ell and ℓ=5\ell = 5.

Exercise 3: Cayley for n=4n = 4 (code)

Count the spanning trees of K4K_4 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.

python · try it yourself
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?

  1. 100
  2. 99
  3. 101
  4. 50

What does Kruskal's algorithm do with an edge that would close a cycle?

  1. Adds it anyway
  2. Skips it
  3. Removes the heaviest edge of the cycle
  4. Stops

How many labelled trees are there on 5 vertices (Cayley)?

  1. 25
  2. 60
  3. 120
  4. 125