Spanning tree
A spanning tree of a graph is a subgraph that is a tree which contains all the vertices in the original graph. Intuitively, spanning trees are trees that "span" every vertex. Due to being trees, they use the fewest number of edges necessary to connect all the vertices.
A disconnected graph has no spanning trees. A tree is its own unique spanning tree.
To construct a spanning tree, perform a depth-first search (DFS) or breadth-first search (BFS) on the graph. Both of these algorithms will traverse the entire graph, but differ in how they prioritize which vertices get explored first.
Depth-first search
In a depth-first search, each branch of the graph is explored as deeply as possible before backtracking. The spanning tree this routine generates is as tall as possible.
algorithm dfs is
input: a connected graph G = (V, E) and starting vertex r
output: a spanning tree of G rooted at r
let T be an empty graph
explore(G, r, T)
return T
This implementation of depth-first search has a recursive subroutine, explore:
subroutine explore is
input: a connected graph G = (V, E), vertex to explore v, and graph T
output: changes T
add v to T
for every edge (v, w) in G
if w not in T
add (v, w) to T
explore(G, w, T)
A non-recursive implementation of depth-first search also exists. It resembles the breadth-first search implementation below, but has one small difference that makes all the difference.
Breadth-first search
In a breadth-first search, vertices are explored in the order of their proximity to the starting vertex. The spanning tree this routine generates is as wide as possible.
algorithm bfs is
input: a connected graph G = (V, E) and starting vertex r
output: a spanning tree of G rooted at r
let T be an empty graph
add r to T
unvisited ← []
append r to unvisited
while unvisited is not empty
remove v from the front of unvisited
for each edge (v, w) in G
if w not in T
add (v, w) to T
add w to T
append w to unvisited
return T