Module contents
Lesson 15 of 22Core 100 min

Trees: characterizations, counting and structure

Trees as a central structure in computer science: equivalent characterizations, rooted and binary trees, traversals and reconstruction, spanning trees, Cayley's formula through the Prüfer bijection, and the matrix-tree theorem. The lesson concludes with the height bound for decision trees, used in m08 to derive the comparison-sorting lower bound.

After this lesson you can

  • Prove the equivalence of the characterizations of a tree.
  • Work with rooted and binary trees: height, depth, and the relation between leaves and internal nodes.
  • Reconstruct a binary tree from traversals and recognize when reconstruction is possible.
  • Prove Cayley's formula using the Prüfer bijection.
  • Count spanning trees using Kirchhoff's theorem.
  • Prove that a binary tree with L leaves has height at least ⌈log2 L⌉.

Before you start

Motivation: the structure everywhere

If you inventory the data structures of a modern machine learning system, almost all are trees or are traversed like trees:

  • Syntax trees. A parser converts (x + 2) * 3 into a tree whose internal nodes are operations and whose leaves are operands. This is the inductive definition of expressions made into a data structure, used by every compiler, interpreter, and automatic differentiation system.
  • Game trees. AlphaZero chooses each move by building a search tree: the root is the current position, children are positions after each legal move, and Monte Carlo search expands it selectively. Minimax is a recursion over that tree.
  • Decision trees. A decision tree (CART), and therefore each tree in a Random Forest or XGBoost, is a rooted binary tree with a predicate xj≤tx_j \le t at each internal node and a prediction at each leaf.
  • Hierarchies and indexes. The file system, a web page’s DOM, a class taxonomy, a database B-tree index, a token trie, a priority heap.
  • Loop-free networks. Ethernet switches run the Spanning Tree Protocol to retain a spanning tree of the network and prevent a broadcast packet from circulating forever; Kruskal’s algorithm chooses the cheapest spanning tree.

Knowing the combinatorics of trees prevents concrete design errors. If a tree with nn nodes always has n−1n - 1 edges, a vector padre of length nn represents it entirely, and checking whether an input is a tree costs O(n)\bigO(n). If there are exactly nn−2n^{n-2} labeled trees, one can be generated uniformly at random to test code (and the naive method of attaching each new vertex to an earlier one is not uniform, as you will see). If a binary tree with LL leaves has height at least ⌈log⁡2L⌉\lceil \log_2 L \rceil, no comparison-sorting algorithm can go below roughly nlog⁡2n−1.44 nn \log_2 n - 1.44\,n comparisons, so there is no need to search for one. This lesson proves those facts and some deeper ones: a determinant counts trees, and Cayley’s count has a proof that is an algorithm.

Intuition: when a graph is a tree

A tree is a connected graph with no cycles. That is the definition, but there are four or five other ways to say the same thing, each useful in a different context. Discover them before proving them.

InteractiveWhen a graph is a tree
✓ Connected
one component
✓ Acyclic
no cycle
✓ n − 1 edges
m = 6, n − 1 = 6
✓ Unique path
between every pair
1234567
This is a tree: all four properties hold. Add or remove an edge and see what changes.
Combinations of C (connected), A (acyclic) and E (m=n−1m = n - 1) seen so far. The failing property is crossed out.
CAE
visto
CAE
¿?
CAE
¿?
CAE
¿?
CAE
·
CAE
·
CAE
·
CAE
·
Dashed cells have exactly two properties. Can you light any of them?
7
edges mm6
components cc1
m−n+cm - n + c (independent cycles)0
Is it a tree?yes
Click two vertices to add or remove the edge joining them (or click an edge to remove it). The four badges light up if the graph is connected, acyclic, has n−1n - 1 edges, and has a unique path between each pair of vertices. Each change explains its effect: a new edge either joins two components or closes a cycle, highlighted in red. The combinations of the first three properties encountered are recorded below. Try lighting a dashed-border cell (exactly two properties true). Also try ‘Trap’ (Trampa) and observe the m−n+cm - n + c reading.

Three things the figure shows, which the next section turns into theorems:

  1. Each new edge does exactly one of two things. If its endpoints were in different components, it joins them and creates no cycle. If they were in the same one, a path already joined them and the edge closes it into a cycle. Never both, never neither.
  2. The “exactly two” cells do not light up. However you try, connected and acyclic requires n−1n - 1 edges; connected with n−1n - 1 edges requires no cycles; and acyclic with n−1n - 1 edges requires connectedness. Any two imply the third.
  3. The number m−n+cm - n + c is never negative, and is 0 exactly when there are no cycles. The “Trap” has n−1n - 1 edges and is not a tree: it has two triangles and an isolated vertex, so m−n+c=6−7+3=2m - n + c = 6 - 7 + 3 = 2.

Equivalent characterizations

We use the vocabulary of graphs, degrees, and subgraphs and paths and connectivity. Every graph in this lesson is simple and finite, with n≥1n \ge 1 vertices, mm edges, and cc connected components. A path does not repeat vertices.

The first lemma formalizes observation 1 from the figure. It drives everything else.

Proof

Every cycle of G+uvG + uv using uvuv contains a path from uu to vv that does not use uvuv, that is, a path in GG. If uu and vv are in different components, no such path exists: no new cycle appears, and the two components merge into one (the others do not change). If they are in the same component, there is a path PP from uu to vv in GG, and PP plus edge uvuv is a cycle; the components do not change because uu and vv were already connected.

∎
Proof

Construct GG by adding its edges one at a time to the edgeless graph, which has nn components. By the preceding lemma, each edge either decreases cc by one or closes a cycle without changing cc. If kk edges close a cycle, at the end c=n−(m−k)c = n - (m - k), that is, m−n+c=k≥0m - n + c = k \ge 0. If GG is acyclic, no edge closed a cycle when added (that cycle would still be in GG), so k=0k = 0. Conversely, if GG has a cycle CC, the last edge of CC to be added joined two vertices already connected by the rest of CC and closed a cycle, so k≥1k \ge 1.

∎

The number m−n+cm - n + c is called the graph’s cyclomatic number, and appears in the figure as “independent cycles.” Later you will see exactly what it counts. With the two lemmas, the characterizations almost follow on their own.

This is the theorem of tree characterizations, and each has its use: 2 is what a program checks, 4 is used in proofs, 5 says a tree is the cheapest way to connect, and 6 that it is the richest way to avoid cycles.

Proof

Write the lemma’s condition as m−n+c≥0m - n + c \ge 0, with equality if and only if GG is acyclic.

1, 2 and 3. If 1 holds, c=1c = 1 and m−n+c=0m - n + c = 0, so m=n−1m = n - 1: 2 and 3 hold. If 2 holds, m−n+c=(n−1)−n+1=0m - n + c = (n - 1) - n + 1 = 0, so GG is acyclic. If 3 holds, m=n−cm = n - c because it is acyclic and m=n−1m = n - 1, so c=1c = 1.

1 and 4. If GG is a tree, at least one path joins each pair because it is connected. If there were two distinct paths PP and QQ from uu to vv, let xx be the last vertex of their shared initial segment (the vertex after which they first separate), and let yy be the first vertex of PP after xx that also lies in QQ (it exists because vv does). The segments of PP and QQ between xx and yy have no interior vertices in common, so together they form a cycle: contradiction. Conversely, if exactly one path joins each pair, GG is connected; and if it had a cycle, two consecutive vertices of the cycle would be joined by their edge and by the rest of the cycle, two distinct paths.

1 and 5. If GG is a tree and remained connected after removing edge uvuv, there would be a path from uu to vv without that edge, which together with it would form a cycle. Conversely, if GG is minimally connected and had a cycle, removing an edge from the cycle would not disconnect it (its endpoints remain joined by the rest of the cycle).

1 and 6. If GG is a tree, uu and vv are in the same component and, by the first lemma, G+uvG + uv has a cycle. Conversely, if GG is maximally acyclic but disconnected, an edge between two components would create no cycle, again by the first lemma.

∎

The first part follows by looking at the endpoints of a maximum-length path; the second, because no path between two other vertices passes through a leaf. The complete proof, and the classical inductive deduction that a tree has n−1n - 1 edges, is the lesson’s first exercise. This lemma is the working tool for almost every induction on trees: remove a leaf, apply the hypothesis, put it back. You will use it three more times in this lesson.

A practical consequence: to decide whether a graph given as an edge list is a tree, it suffices to check m=n−1m = n - 1 (free) and connectivity (one traversal, O(n)\bigO(n) because you already know m=n−1m = n - 1). In an edge stream without memory for the whole graph, a union-find structure detects the first edge closing a cycle in nearly constant time per edge, exactly the first lemma turned into an algorithm.

Rooted and binary trees

In computer science almost all trees have a root. Thanks to characterization 4, choosing a vertex suffices to orient the whole tree.

Two conventions can cause off-by-one errors. Height counts edges: a single-node tree has height 0, and the empty tree is assigned −1-1. And “leaf” changes meaning upon rooting: the root of a path r−a−br - a - b has degree 1 but is not a leaf of the rooted tree because it has a child.

A rooted tree also admits a recursive definition, the one programs use: a rooted tree is a root together with a possibly empty collection of rooted trees, its subtrees. Thus functions on trees are structural recursions and their properties are proved by structural induction. The most compact representation is the parent vector: padre[v] for each v≠rv \ne r, n−1n - 1 entries. Such a vector represents a rooted tree if and only if following parents from any vertex reaches rr without repetition, which is what union-find forests maintain.

The definition distinguishes left from right: a node with only a left child and one with only a right child are different binary trees, although as ordered rooted trees they are the same. Thus there are Cn=(2nn)/(n+1)C_n = \binom{2n}{n}/(n + 1) binary trees with nn nodes, the Catalan numbers 1,1,2,5,14,42,132,429,…1, 1, 2, 5, 14, 42, 132, 429, \dots: the recurrence Cn=∑kCkCn−1−kC_{n} = \sum_{k} C_k C_{n-1-k} chooses the size kk of the left subtree. The names “full” and “complete” are not universal (Knuth calls a full tree extended, and full, complete, and perfect are used with overlapping meanings): always check the definition in the text you read. Together, these objects are rooted and binary trees.

Proof

Count edges in two ways (double counting from lesson 10). Each node except the root hangs from exactly one edge leading up to its parent: there are n−1n - 1 edges, with n=n0+n1+n2n = n_0 + n_1 + n_2. Each node has as many downward edges as children: there are n1+2n2n_1 + 2n_2. Equating gives n0+n1+n2−1=n1+2n2n_0 + n_1 + n_2 - 1 = n_1 + 2n_2, that is, n0=n2+1n_0 = n_2 + 1. In a full tree n1=0n_1 = 0 and I=n2I = n_2.

∎

The same equality follows by structural induction (in tree (L,x,R)(L, x, R) with both subtrees nonempty, leaves add and two-child nodes add plus one). In a CART decision tree, which is full, it says a tree with LL leaves has exactly L−1L - 1 splits. In an elimination tournament with LL participants, each match eliminates one: L−1L - 1 matches.

Proof

By induction on dd: level 0 is the root, and each node at level dd contributes at most two to level d+1d + 1. Summing gives n≤1+2+⋯+2h=2h+1−1n \le 1 + 2 + \cdots + 2^h = 2^{h+1} - 1, hence h+1≥log⁡2(n+1)h + 1 \ge \log_2(n + 1) and, since it is an integer, h+1≥⌈log⁡2(n+1)⌉h + 1 \ge \lceil \log_2(n + 1) \rceil. A complete tree of height hh has full levels 0,…,h−10, \dots, h - 1 and at least one node at hh: 2h≤n≤2h+1−12^h \le n \le 2^{h+1} - 1, that is, h=⌊log⁡2n⌋h = \lfloor \log_2 n \rfloor.

∎

The complete tree has minimum height and is stored in an array without pointers: with indices starting at 1, the children of node ii are 2i2i and 2i+12i + 1, and its parent is ⌊i/2⌋\lfloor i/2 \rfloor. This is the shape of the binary heap.

Traversals and reconstruction

Traversing a rooted tree means visiting all its nodes in an order fixed by its structure. Besides level-order traversal, which is breadth-first traversal from the root, there are three canonical recursive orders.

These are the preorder, inorder, and postorder traversals. There is a way to see all three at once. Walk around the tree’s outline, starting to the left of the root and moving counterclockwise: you pass each node three times, on its left while descending, below it between its two subtrees, and on its right while ascending. Writing the key at first contact gives preorder; at the second, inorder; at the third, postorder. This is the tree’s Euler tour, animated by the “Traverse” (Recorrer) mode in the next figure.

Each order has its use. Preorder visits a node before its subtree: it is useful for copying or serialization (create the node first, then its children) and, in an expression tree, gives Polish notation × + x 2 3\times\, +\, x\, 2\, 3. Postorder visits a node after its subtree: it is the evaluation order (operands before the operation, as in reverse Polish notation x 2+3 ×x\, 2 + 3\, \times and stack-machine code such as Python bytecode), the order for freeing memory, and the order for any bottom-up dynamic programming, such as computing sizes or heights. The inorder traversal of a binary search tree is its sorted list of keys.

Which traversals determine the tree?

One traversal is not enough. The tree rooted at BB with left child AA and the tree rooted at AA with right child BB have the same inorder, A BA\,B; and root AA with a single child BB gives the same preorder, A BA\,B, whether BB hangs on the left or right. What about two traversals?

Proof

Use strong induction on the number of nodes nn. With n=0n = 0 the tree is empty. Let n≥1n \ge 1 and let T=(L,x,R)T = (L, x, R) be any tree with preorder pp and inorder qq. The root must be x=p1x = p_1, the first element of preorder. Since keys are distinct, xx appears exactly once in qq, say at position k+1k + 1. By the definition of inorder, q1⋯qk=in⁡(L)q_1 \cdots q_k = \operatorname{in}(L) and qk+2⋯qn=in⁡(R)q_{k+2} \cdots q_n = \operatorname{in}(R), so LL has kk nodes. By the definition of preorder, p2⋯pk+1=pre⁡(L)p_2 \cdots p_{k+1} = \operatorname{pre}(L) and pk+2⋯pn=pre⁡(R)p_{k+2} \cdots p_n = \operatorname{pre}(R). All of this is fixed by pp and qq, with no choice. By the induction hypothesis, LL is determined by (pre⁡(L),in⁡(L))(\operatorname{pre}(L), \operatorname{in}(L)) and RR by (pre⁡(R),in⁡(R))(\operatorname{pre}(R), \operatorname{in}(R)), hence so is TT. With postorder, the root is the last element and the argument is identical.

∎

The proof is a recursive algorithm. Written directly, searching for the root in inorder costs O(n)\bigO(n) per call and O(n2)\bigO(n^2) in total in the worst case; with a position dictionary built once and consuming preorder with an iterator instead of copying slices, the total drops to O(n)\bigO(n). You will implement it below.

InteractiveReconstructing a tree from traversals
start
preEBHAFCGDinHBFAECDG
Step 0: no nodes built. The root is the first preorder element.
Mode
preorderE B H A F C G D
inorderH B F A E C D G
postorderH F A B D G C E
nodes with one child3 (A, C, G)
The drawing's columns are inorder positions, so the ‘in’ row is directly below its nodes. In ‘Pre + in’, play step by step: each call's root (highlighted) comes from preorder, and its column splits inorder into the left subtree (amber) and right subtree (purple), which in turn fix the preorder segments. In ‘Traverse’ (Recorrer), watch the contour walk write all three traversals. In ‘Pre + post’, the gallery shows all trees with those two traversals: what is special about nodes marked in red? Try the full tree and the zigzag.

With preorder and postorder the argument breaks at exactly one point. The root is p1=snp_1 = s_n (with ss the postorder), and if n≥2n \ge 2 the second element of preorder, c=p2c = p_2, is the root of the first nonempty subtree. In postorder, cc is last in that subtree, so everything in ss up to cc is that subtree. If that is all that remains, the root has one child… and nothing in pp or ss says whether it is left or right.

Proof

Use strong induction on nn, following the previous argument. If n≤1n \le 1 there is one tree and k=0k = 0. If n≥2n \ge 2, let c=p2c = p_2 and let jj be its position in ss. If j<n−1j < n - 1, the root has two children: the first subtree consists of s1⋯sjs_1 \cdots s_j and the second of sj+1⋯sn−1s_{j+1} \cdots s_{n-1}, the corresponding preorder segments are fixed, and the number of trees is the product 2k1⋅2k2=2k1+k22^{k_1} \cdot 2^{k_2} = 2^{k_1 + k_2} by induction. If j=n−1j = n - 1, the root has one child, whose subtree has preorder p2⋯pnp_2 \cdots p_n and postorder s1⋯sn−1s_1 \cdots s_{n-1}; it can hang left or right, and the count is 2⋅2k′=2k′+12 \cdot 2^{k'} = 2^{k' + 1}, with the root counted among one-child nodes. The number kk is determined by pp and ss because the recursion is.

∎

The proposition also explains why one traversal suffices in two common cases. A Polish-notation expression is reconstructed without parentheses because each symbol gives its number of children (binary operators two, operands none). And the serialization format writing preorder with each empty subtree marked (for example A B # # C # #) is unambiguous for the same reason: each node declares both children. What preorder and postorder together lack is exactly that information, node by node.

Spanning trees

Proof

If T⊆GT \subseteq G is a spanning tree, every pair of vertices is joined by a path in TT, which also lies in GG. Conversely, if GG is connected, remove edges one at a time while the graph remains connected. The process terminates (there are finitely many) in a connected spanning subgraph from which no edge can be removed without disconnecting it: minimally connected, hence a tree by characterization 5.

∎

The proof is inefficient, but direct constructions exist: a breadth-first or depth-first traversal tree from any vertex spans the graph, as does adding edges one at a time and discarding those that close a cycle (the first lemma). If edges are also processed from lowest to highest weight, the result is a minimum spanning tree: Kruskal’s algorithm, studied in m08.

The cycle space

Fix a spanning tree TT of a connected graph GG. There are m−(n−1)=m−n+1m - (n - 1) = m - n + 1 edges outside TT, and each, e=uve = uv, closes with the unique path from uu to vv in TT a cycle CeC_e, the fundamental cycle of ee. Also, if you remove any edge f≠ef \ne e from CeC_e, T+e−fT + e - f is another spanning tree (connected with n−1n - 1 edges): this is the exchange property used to prove Kruskal correct.

Why was the cyclomatic number m−n+cm - n + c called “independent cycles”? Represent each edge set by its indicator vector in {0,1}m\{0, 1\}^m and add them modulo 2 (symmetric difference). Subgraphs in which all vertices have even degree (exactly unions of cycles with no shared edges) form a subspace of F2m\mathbb{F}_2^m: the modulo-2 sum of two still has all degrees even. This is the cycle space.

Proof

Independent: each CeC_e contains exactly one edge outside TT, its own; in any sum of several, edge ee of each summand appears only in that summand and does not cancel. Spanning: let ZZ be an even-degree subgraph and let Z′=Z+∑e∈Z∖TCeZ' = Z + \sum_{e \in Z \setminus T} C_e. Each edge outside TT appears in Z′Z' an even number of times (once in ZZ and once in its CeC_e), so Z′⊆TZ' \subseteq T, and Z′Z' has even degrees. But a nonempty subgraph of TT is a forest with an edge, and a component with edges is a tree with at least two leaves, of degree 1. Thus Z′=∅Z' = \varnothing and Z=∑e∈Z∖TCeZ = \sum_{e \in Z \setminus T} C_e.

∎

Notice that the proof again uses the two-leaf lemma. This is the topic’s historical origin: in 1847 Kirchhoff needed to know how many independent mesh equations an electrical circuit has, and the answer is m−n+1m - n + 1, one for each edge outside a spanning tree. The same paper contains his spanning-tree counting theorem, which we will see in two sections.

Cayley’s formula

How many distinct trees have vertices {1,…,n}\{1, \dots, n\}? Here vertices are named: two trees are equal if they have exactly the same edges, even if they have the same shape. With n=3n = 3 there are 3 (the central vertex is 1, 2, or 3). With n=4n = 4 there are two shapes, the path and the star: 4!/2=124!/2 = 12 paths (an ordering of vertices up to reversal) and 4 stars (choice of center), 16 total. With n=5n = 5 there are three shapes: 60 paths, 5 stars, and 60 “chairs” (5 choices of the degree-3 vertex, 4 of the degree-2 vertex, and 3 of the leaf hanging from the latter), 125 total. The sequence 1,1,3,16,1251, 1, 3, 16, 125 is nn−2n^{n-2}.

Notice the contrast: with 6 vertices there are only 6 tree shapes, but 64=12966^4 = 1296 labeled trees. And nn−2n^{n-2} is the number of sequences of length n−2n - 2 with values in {1,…,n}\{1, \dots, n\}, suggesting a bijection and the bijection rule.

The example’s final observation is the lemma that explains everything.

Proof

An edge disappears from the tree only when one endpoint is removed as a leaf. Follow the edges of vv: while vv is in the tree, whenever a neighbor (which was a leaf) is removed, vv is recorded. Vertex vv stops losing neighbors when it is itself removed as a leaf, with one remaining, or at the end, when it remains with another vertex on the last edge. In both cases it has lost exactly deg⁡T(v)−1\deg_T(v) - 1 neighbors and has been recorded once for each.

∎
Proof

Use induction on nn, over arbitrary vertex sets of nn numbers (the algorithm only uses label order). For n=2n = 2 there is one tree and one sequence, the empty one. Let n≥3n \ge 3 and let s=(s1,…,sn−2)s = (s_1, \dots, s_{n-2}) be any sequence over a set VV of nn labels. Call ℓ\ell the smallest element of VV absent from ss (it exists because ss has n−2n - 2 terms and VV has nn elements).

At most one tree has code ss. If TT has code ss, by the lemma its leaves are the elements of VV absent from ss, so the first leaf removed is ℓ\ell, its neighbor is s1s_1, and T−ℓT - \ell is a tree on V∖{ℓ}V \setminus \{\ell\} with code (s2,…,sn−2)(s_2, \dots, s_{n-2}), because the algorithm on TT continues exactly as on T−ℓT - \ell. By the induction hypothesis T−ℓT - \ell is determined, and so is T=(T−ℓ)+ℓs1T = (T - \ell) + \ell s_1.

At least one tree has code ss. The sequence (s2,…,sn−2)(s_2, \dots, s_{n-2}) does not contain ℓ\ell, so by hypothesis there is a tree T′T' on V∖{ℓ}V \setminus \{\ell\} with that code. Let T=T′+ℓs1T = T' + \ell s_1, which is a tree because a leaf is added. By the lemma applied to T′T', its leaves are the elements of V∖{ℓ}V \setminus \{\ell\} absent from (s2,…,sn−2)(s_2, \dots, s_{n-2}); in TT, s1s_1 gains a neighbor, so the leaves of TT are ℓ\ell and the elements of VV absent from ss. The smallest is ℓ\ell, removed first while recording s1s_1, and the rest of the algorithm is that of T′T'. The code of TT is ss.

∎

This result, Cayley’s formula with the Prüfer bijection, has a proof that is also a decoding algorithm: at each step join the first pending number in the sequence to the smallest unused vertex that no longer appears in the remainder; finally, join the two remaining vertices.

InteractiveThe Prüfer bijection
Prüfer sequence ss
4
6
4
2
6
complete
1234567
A tree and its Prüfer sequence. Play to see how each is obtained from the other.
vertex1234567occurrences in ss0102020degree1213131
Always degree⁡(v)=1+\operatorname{degree}(v) = 1 + (number of times vv appears in ss). Leaves are red.
Direction
7
Tree number9 078 of 16 807
nn−2n^{n-2} with n=7n = 716 807
Leaves (absent from sequence)1, 3, 5, 7
encode(decode(s)) = syes
Change sequence numbers with the arrows and watch the tree change: each sequence gives a different tree, and ‘Next’ (Siguiente) visits them all in order. Play ‘Encode’ (Codificar: remove the smallest-labeled leaf, in red, and record its neighbor, in blue) and ‘Decode’ (Decodificar: join the first pending number to the smallest vertex no longer appearing). Check that the two animations traverse the same edges in the same order, and that in the table below each vertex's degree is always one more than its occurrences in the sequence.

The degree lemma gives more than the total count. A tree with prescribed degrees d1,…,dnd_1, \dots, d_n (with ∑idi=2(n−1)\sum_i d_i = 2(n - 1), all ≥1\ge 1) corresponds to a sequence in which each ii appears di−1d_i - 1 times, and such sequences are counted by a multinomial coefficient:

#{T:deg⁡T(i)=di}=(n−2)!(d1−1)! (d2−1)!⋯(dn−1)!.\#\{T : \deg_T(i) = d_i\} = \frac{(n - 2)!}{(d_1 - 1)!\,(d_2 - 1)! \cdots (d_n - 1)!}.

Summing over all degrees recovers nn−2n^{n-2} by the multinomial theorem. Other immediate consequences: there are (n−1)n−2(n - 1)^{n-2} trees in which vertex 1 is a leaf (sequences without 1), so in a uniformly random tree the probability that a given vertex is a leaf is (1−1/n)n−2→1/e≈0.368(1 - 1/n)^{n-2} \to 1/e \approx 0.368. To generate a tree uniformly at random, simply generate a uniform sequence and decode it. The naive method of attaching each vertex v=2,…,nv = 2, \dots, n to a randomly chosen earlier vertex produces the random recursive tree, which is not uniform: with n=3n = 3 vertex 3 is never the center and the other two are each the center with probability 1/21/2, instead of 1/31/3.

The matrix-tree theorem

Cayley counts spanning trees of the complete graph KnK_n. What about an arbitrary graph? Kirchhoff’s answer is a determinant.

Three properties are apparent. L\mat{L} is symmetric. Every row sums to 0, so L1=0\mat{L}\vb{1} = \vb{0} and det⁡L=0\det\mat{L} = 0: that is why a row and column must be removed. And L\mat{L} factors. Orient each edge arbitrarily and form the incidence matrix B∈Rn×m\mat{B} \in \R^{n \times m}, whose column for edge ee from uu to vv has +1+1 in row uu, −1-1 in row vv, and zeros elsewhere. Then

L=BB⊤,x⊤Lx=∑uv∈E(xu−xv)2≥0,\mat{L} = \mat{B}\mat{B}\T, \qquad \vb{x}\T\mat{L}\vb{x} = \sum_{uv \in E} (x_u - x_v)^2 \ge 0,

because (BB⊤)ii(\mat{B}\mat{B}\T)_{ii} counts columns with a ±1\pm 1 in row ii (the degree) and (BB⊤)ij=(+1)(−1)=−1(\mat{B}\mat{B}\T)_{ij} = (+1)(-1) = -1 if ijij is an edge. The spectral properties making this matrix a central tool of graph analysis are studied with the combinatorial Laplacian.

This is Kirchhoff’s matrix-tree theorem. Check it before proving it.

InteractiveCounting spanning trees with a determinant
12345
Laplacian L=D−A\mat{L} = \mat{D} - \mat{A}
123452−1−100−13−1−10−1−130−10−102−100−1−12
Diagonal: degrees. Off diagonal, −1-1 per edge. Each row sums to 00.
Gallery: 11 spanning trees. Reduced Laplacian determinant: 11. ✓ They match.
Deleted row and column
trees in the gallery11
det⁡L~\det \tilde{\mat{L}} (without row and column 1)11
the nn diagonal cofactorsall 11
subsets of n−1n - 1 edges tested15
The gallery enumerates by brute force all subsets of n−1n - 1 edges forming a tree; alongside is the Laplacian with one row and its column crossed out. Hover over a thumbnail to see its tree on the graph. Compare gallery size with the determinant, change the crossed-out row (the nn cofactors are equal), and edit the graph by clicking pairs of vertices: remove an edge from the house and guess the new number before looking. What happens when the graph is disconnected?

The proof combines three pieces: the factorization L=BB⊤\mat{L} = \mat{B}\mat{B}\T, the Cauchy–Binet formula, and a lemma translating “being a tree” into the language of determinants.

Cauchy–Binet. If P\mat{P} is k×mk \times m and Q\mat{Q} is m×km \times k with k≤mk \le m, then det⁡(PQ)=∑Sdet⁡P[:,S]det⁡Q[S,:]\det(\mat{P}\mat{Q}) = \sum_S \det\mat{P}_{[:,S]} \det\mat{Q}_{[S,:]}, where SS ranges over subsets of kk columns of P\mat{P} (the same kk rows of Q\mat{Q}). If k>mk > m, the rank of PQ\mat{P}\mat{Q} is less than kk and the determinant is 0. This generalizes det⁡(PQ)=det⁡Pdet⁡Q\det(\mat{P}\mat{Q}) = \det\mat{P}\det\mat{Q} to rectangular matrices.

Proof

If (V,S)(V, S) is not a tree, since it has n−1n - 1 edges, characterization 2 says it is disconnected. Let KK be a component not containing vv. Sum the rows of Bv[S]\mat{B}_v[S] corresponding to vertices of KK: every edge of SS has both endpoints in KK (contributing +1−1=0+1 - 1 = 0) or neither (contributing 0), because no edge leaves a component. The rows are dependent and the determinant is 0.

If (V,S)(V, S) is a tree, use induction on nn. With n=1n = 1, S=∅S = \varnothing and the matrix is 0×00 \times 0, with determinant 1. With n≥2n \ge 2, the tree has at least two leaves, so a leaf uu differs from vv. The row of uu in Bv[S]\mat{B}_v[S] has one nonzero entry, ±1\pm 1, in the column of the unique edge ee of uu. Expanding along that row (cofactor expansion), det⁡Bv[S]=±det⁡M\det\mat{B}_v[S] = \pm\det\mat{M}, where M\mat{M} is the matrix without row uu or column ee: exactly the incidence matrix, without the row of vv, of tree T−uT - u on n−1n - 1 vertices. By the induction hypothesis, det⁡M=±1\det\mat{M} = \pm 1.

∎
Proof

(Of the theorem.) Removing row and column vv from L=BB⊤\mat{L} = \mat{B}\mat{B}\T means removing row vv from B\mat{B} and column vv from B⊤\mat{B}\T: L~v=BvBv⊤\tilde{\mat{L}}_v = \mat{B}_v\mat{B}_v\T. By Cauchy–Binet with k=n−1k = n - 1,

det⁡L~v=∑∣S∣=n−1det⁡Bv[S]det⁡Bv[S]⊤=∑∣S∣=n−1(det⁡Bv[S])2.\det\tilde{\mat{L}}_v = \sum_{\abs{S} = n - 1} \det\mat{B}_v[S] \det\mat{B}_v[S]\T = \sum_{\abs{S} = n - 1} \big(\det\mat{B}_v[S]\big)^2.

By the lemma, each term is 1 if SS is a spanning tree and 0 otherwise. The sum counts spanning trees. If m<n−1m < n - 1 both sides are 0.

∎

The entire proof rests on earlier results: characterization 2 excludes sets that are not trees, the two-leaf lemma enables induction, and removing a leaf leaves a tree. The sign ±1\pm 1 depends on the chosen orientation, but it is squared.

Three useful extensions. If every edge has weight wew_e and the Laplacian is weighted (Lii=∑e∋iweL_{ii} = \sum_{e \ni i} w_e, Lij=−wijL_{ij} = -w_{ij}), the same argument gives det⁡L~v=∑T∏e∈Twe\det\tilde{\mat{L}}_v = \sum_T \prod_{e \in T} w_e, the sum over spanning trees of the product of their weights. For directed graphs, Tutte’s theorem similarly counts arborescences pointing to a root. In eigenvalue terms, τ(G)=1nλ2⋯λn\tau(G) = \frac{1}{n}\lambda_2 \cdots \lambda_n, the product of the nonzero eigenvalues of L\mat{L} divided by nn.

Decision trees and the sorting bound

A comparison-based sorting algorithm can obtain information about its input only by asking “is ai<aja_i < a_j?” For fixed size nn, everything it does fits in a binary tree: each internal node is a comparison, its two children are what the algorithm does depending on the answer, and each leaf is an end of execution, with the permutation the algorithm applies to the input. Running the algorithm on an input follows a path from root to leaf, and the number of comparisons is that path’s length. The worst case is the tree’s height.

This is the decision-tree height bound. Two observations are essential. First, L≤2hL \le 2^h, by structural induction: a leaf has 1=201 = 2^0, and a node whose subtrees have height ≤h−1\le h - 1 has at most 2h−1+2h−12^{h-1} + 2^{h-1} leaves; since hh is an integer, h≥⌈log⁡2L⌉h \ge \lceil \log_2 L \rceil. Second, each of the n!n! possible input orders needs its own leaf: if two different orders reached the same leaf, the algorithm would apply the same permutation to both and one would be left unsorted. You will complete the details in a guided exercise.

How large is log⁡2n!\log_2 n!? From n!≥(n/e)nn! \ge (n/e)^n follows log⁡2n!≥nlog⁡2n−nlog⁡2e\log_2 n! \ge n\log_2 n - n\log_2 e, and Stirling’s formula sharpens it: log⁡2n!=nlog⁡2n−nlog⁡2e+12log⁡2(2πn)+o(1)\log_2 n! = n\log_2 n - n\log_2 e + \tfrac{1}{2}\log_2(2\pi n) + o(1). No comparison sort goes below nlog⁡2n−1.443 nn\log_2 n - 1.443\,n in the worst case: mergesort, which makes at most n⌈log⁡2n⌉−2⌈log⁡2n⌉+1n\lceil\log_2 n\rceil - 2^{\lceil \log_2 n\rceil} + 1, is optimal up to a linear term. This is the comparison-sorting lower bound, revisited in m08.

nn4581012
⌈log⁡2n!⌉\lceil \log_2 n! \rceil57162229
mergesort, worst case58172533
merge-insertion (Ford–Johnson)57162230

The bound is not always attained: for n=12n = 12 exhaustive search shows (Wells, 1965) that 30 comparisons are needed, one more than ⌈log⁡212!⌉=29\lceil \log_2 12! \rceil = 29 says. The clearest way to see why the bound is unavoidable is to play against an adversary.

InteractiveSorting against an adversary
What you know: an arrow x→yx \to y means x<yx < y (only those not implied by others).
abcd
The 4!=244! = 24 possible orders; colored ones agree with the answers
Answers
  1. a < b 24 → 12
The answer left 12 of 24 orders (50%). The adversary always keeps the larger half, so you never drop below half.
Elements nn
Who answers
comparisons made1
compatible orders ∣S∣\abs{S}12 of 24
still needed, ⌈log⁡2∣S∣⌉\lceil \log_2 \abs{S} \rceil4
bound ⌈log⁡24!⌉\lceil \log_2 4! \rceil5
You act as the algorithm: click two elements to compare them. The adversary has no fixed order; it responds to leave more grid orders compatible. Each answer turns off at most half the cells, so after kk comparisons at least n!/2kn!/2^k remain and you cannot finish before ⌈log⁡2n!⌉\lceil \log_2 n! \rceil. The diagram above is the order you already know: comparing elements joined by a path of arrows adds nothing. Try reaching the bound with n=4n = 4 (5 comparisons) and n=5n = 5 (7). Then switch to ‘Fixed hidden order’ (Orden oculto fijo): sometimes you finish earlier because the bound is for the worst case.

The adversary is the proof as a game: if SS is the set of orders compatible with the answers given, a comparison splits it in two and the adversary keeps the larger half, of size at least ∣S∣/2\abs{S}/2. There is also an information interpretation: identifying one permutation among n!n! requires log⁡2n!\log_2 n! bits and each comparison gives at most one. Thus the bound does not apply to algorithms that inspect values instead of comparing them, such as counting sort or radix sort, which sort bounded integers in linear time.

What about the average case? The bound survives: the mean depth of leaves in a binary tree with LL leaves is at least log⁡2L\log_2 L.

Proof

Kraft’s inequality follows by structural induction: a single leaf contributes 20=12^0 = 1; if the root has subtrees T1T_1 and (perhaps) T2T_2, each leaf is one level lower than in its subtree, so the sum is 12(Σ1+Σ2)≤12(1+1)=1\frac{1}{2}(\Sigma_1 + \Sigma_2) \le \frac{1}{2}(1 + 1) = 1. For the mean, the function t↦2−tt \mapsto 2^{-t} is convex, and by Jensen’s inequality 2−dˉ≤1L∑i2−di≤1L2^{-\bar d} \le \frac{1}{L}\sum_i 2^{-d_i} \le \frac{1}{L}, where dˉ\bar d is the mean. Taking logarithms gives dˉ≥log⁡2L\bar d \ge \log_2 L.

∎

Thus even averaged over the n!n! equiprobable inputs, a comparison sort makes at least log⁡2n!\log_2 n! comparisons. Kraft’s inequality also governs prefix codes: a binary code is a tree whose leaves are codewords, and its average length is at least the entropy. Huffman trees, which attain that minimum, are full binary trees built using this lesson’s combinatorics.

Implementation from scratch

First, recognize a tree. Function componentes turns the first lemma into an algorithm: add edges one at a time in union-find and count those joining components. Then, for all graphs with vertices {0,…,n−1}\{0, \dots, n - 1\} up to n=6n = 6, check that any two of the three properties imply the third and, up to n=5n = 5, that the unique-path characterization agrees. As a bonus, the number of trees among those graphs matches Cayley’s formula.

[ ]Characterizations checked on all small graphsBrowser
from itertools import combinations

def componentes(n, aristas):
    """Número de componentes y si alguna arista cerró un ciclo (union-find)."""
    padre, tam = list(range(n)), [1] * n
    def raiz(x):
        while padre[x] != x:
            padre[x] = padre[padre[x]]          # compresión de caminos (a medias)
            x = padre[x]
        return x
    c, ciclo = n, False
    for u, v in aristas:
        ru, rv = raiz(u), raiz(v)
        if ru == rv:                            # ya estaban conectados: la arista cierra un ciclo
            ciclo = True
            continue
        if tam[ru] < tam[rv]:
            ru, rv = rv, ru
        padre[rv] = ru                          # unión por tamaño
        tam[ru] += tam[rv]
        c -= 1                                  # la arista une dos componentes
    return c, ciclo

def es_arbol(n, aristas):
    return len(aristas) == n - 1 and componentes(n, aristas)[0] == 1

def caminos_simples(n, aristas, a, b):
    ady = [[] for _ in range(n)]
    for u, v in aristas:
        ady[u].append(v); ady[v].append(u)
    cuenta, vistos = 0, {a}
    def dfs(u):
        nonlocal cuenta
        if u == b:
            cuenta += 1
            return
        for w in ady[u]:
            if w not in vistos:
                vistos.add(w); dfs(w); vistos.discard(w)
    dfs(a)
    return cuenta

for n in range(2, 7):
    pares = list(combinations(range(n), 2))
    arboles = fallos = 0
    for mascara in range(1 << len(pares)):                 # todos los grafos con n vértices
        E = [pares[i] for i in range(len(pares)) if mascara >> i & 1]
        c, ciclo = componentes(n, E)
        C, A, M = c == 1, not ciclo, len(E) == n - 1
        fallos += (C and A) != (C and M) or (C and A) != (A and M)
        if n <= 5:
            unico = all(caminos_simples(n, E, a, b) == 1 for a, b in pares)
            fallos += unico != (C and A)
        arboles += es_arbol(n, E)
    print(f"n = {n}: {1 << len(pares):6d} grafos, {arboles:5d} árboles, "
          f"n^(n-2) = {n ** (n - 2):5d}, contraejemplos: {fallos}")

None of the 33,866 graphs is a counterexample, and the tree counts are 1,3,16,125,12961, 3, 16, 125, 1296. Next come traversals and reconstruction in O(n)\bigO(n). A tree is a triple (clave, izq, der) or None. To check the theorem, generate all binary-tree shapes with nn nodes (giving Catalan numbers) and label them in preorder, so preorder is always 0,1,…,n−10, 1, \dots, n - 1 and two trees share preorder and postorder if and only if they share postorder.

[ ]Traversals, reconstruction, and the 2^k lawBrowser
from collections import Counter

def preorden(t):  return [] if t is None else [t[0]] + preorden(t[1]) + preorden(t[2])
def inorden(t):   return [] if t is None else inorden(t[1]) + [t[0]] + inorden(t[2])
def postorden(t): return [] if t is None else postorden(t[1]) + postorden(t[2]) + [t[0]]

def reconstruir(pre, ino):
    """Árbol a partir del preorden y el inorden (claves distintas), en O(n)."""
    pos = {k: i for i, k in enumerate(ino)}      # posición de cada clave en el inorden
    raices = iter(pre)                            # el preorden da las raíces en orden de creación
    def construir(lo, hi):                        # subárbol cuyo inorden es ino[lo:hi]
        if lo >= hi:
            return None
        raiz = next(raices)
        r = pos[raiz]
        izq = construir(lo, r)                    # primero el izquierdo: es el que sigue en el preorden
        der = construir(r + 1, hi)
        return (raiz, izq, der)
    return construir(0, len(ino))

def formas(n):
    """Todos los árboles binarios con n nodos, sin claves."""
    if n == 0:
        yield None
        return
    for k in range(n):                            # k nodos en el subárbol izquierdo
        for izq in formas(k):
            for der in formas(n - 1 - k):
                yield (None, izq, der)

def etiquetar(t, claves):
    if t is None:
        return None
    k = next(claves)
    return (k, etiquetar(t[1], claves), etiquetar(t[2], claves))

def hijo_unico(t):
    if t is None:
        return 0
    return ((t[1] is None) != (t[2] is None)) + hijo_unico(t[1]) + hijo_unico(t[2])

for n in range(1, 9):
    arboles = [etiquetar(f, iter(range(n))) for f in formas(n)]
    ok = all(reconstruir(preorden(t), inorden(t)) == t for t in arboles)
    clases = Counter(tuple(postorden(t)) for t in arboles)
    ley = all(clases[tuple(postorden(t))] == 2 ** hijo_unico(t) for t in arboles)
    print(f"n = {n}: {len(arboles):4d} árboles, pre + in reconstruye todos: {ok}, "
          f"pares (pre, post) distintos: {len(clases):3d}, ley 2^k: {ley}")

The tree column gives Catalan numbers, distinct pairs give Motzkin numbers, and each class contains exactly 2k2^k trees. A practical detail: these recursive functions fail on very deep trees because Python limits recursion depth (to 1000 by default). A degenerate tree, such as a search tree built by inserting already sorted keys, easily reaches that limit. The explicit-stack version has no such limit.

[ ]Traversals without recursionBrowser
peine = None
for k in range(5000):                  # un árbol degenerado: cada nodo solo tiene hijo izquierdo
    peine = (k, peine, None)

try:
    preorden(peine)
except RecursionError as e:
    print("versión recursiva:", type(e).__name__)

def preorden_iterativo(t):
    salida, pila = [], [t]
    while pila:
        u = pila.pop()
        if u is not None:
            salida.append(u[0])
            pila.append(u[2])          # el derecho se apila primero para salir después
            pila.append(u[1])
    return salida

r = preorden_iterativo(peine)
print("versión iterativa:", len(r), "nodos, empieza por", r[:4])

Now Prüfer. Both functions use a heap to obtain the smallest leaf (or smallest free vertex) in O(log⁡n)\bigO(\log n), so they cost O(nlog⁡n)\bigO(n \log n); the direct version searching for the minimum at every step costs O(n2)\bigO(n^2). The bijection is checked by complete enumeration up to n=7n = 7: each of the nn−2n^{n-2} sequences gives a valid tree, encoding it recovers the sequence, the degree lemma holds, and all resulting trees are distinct.

[ ]Prüfer from scratch, with the bijection checkedBrowser
import heapq
from itertools import product
from collections import Counter

def prufer_codificar(n, aristas):
    """Árbol con vértices 1..n -> sucesión de Prüfer de longitud n - 2."""
    ady = {v: set() for v in range(1, n + 1)}
    for u, v in aristas:
        ady[u].add(v); ady[v].add(u)
    hojas = [v for v in ady if len(ady[v]) == 1]
    heapq.heapify(hojas)
    s = []
    for _ in range(n - 2):
        hoja = heapq.heappop(hojas)             # la hoja de menor etiqueta
        vecino = ady[hoja].pop()
        s.append(vecino)
        ady[vecino].discard(hoja)
        if len(ady[vecino]) == 1:               # el vecino acaba de quedarse en hoja
            heapq.heappush(hojas, vecino)
    return s

def prufer_decodificar(s):
    """Sucesión de longitud n - 2 sobre 1..n -> lista de aristas del árbol."""
    n = len(s) + 2
    pendientes = Counter(s)                     # apariciones que le quedan a cada vértice
    libres = [v for v in range(1, n + 1) if pendientes[v] == 0]
    heapq.heapify(libres)
    aristas = []
    for x in s:
        hoja = heapq.heappop(libres)            # el menor que ya no aparece en lo que queda
        aristas.append((hoja, x))
        pendientes[x] -= 1
        if pendientes[x] == 0:
            heapq.heappush(libres, x)
    aristas.append((heapq.heappop(libres), heapq.heappop(libres)))
    return aristas

canon = lambda E: frozenset(frozenset(e) for e in E)
for n in range(2, 8):
    arboles = set()
    for s in product(range(1, n + 1), repeat=n - 2):
        E = prufer_decodificar(list(s))
        assert len(canon(E)) == n - 1                          # n - 1 aristas distintas
        assert prufer_codificar(n, E) == list(s)               # codificar(decodificar(s)) = s
        grado = Counter(v for e in E for v in e)
        assert all(grado[v] == 1 + s.count(v) for v in range(1, n + 1))   # lema de los grados
        arboles.add(canon(E))
    print(f"n = {n}: {n ** (n - 2):6d} sucesiones -> {len(arboles):6d} árboles distintos")

print("código del ejemplo:", prufer_codificar(7, [(1, 4), (3, 6), (5, 4), (4, 2), (2, 6), (6, 7)]))

Since every sequence decodes to a tree with n−1n - 1 edges that encodes back to it, decoding is injective, and nn−2n^{n-2} distinct trees arise from nn−2n^{n-2} sequences. The theorem guarantees all are trees (not graphs with cycles); the first cell confirmed this another way by counting trees among all graphs. With decoding in hand, generating uniform trees is trivial. Compare the naive method:

[ ]Uniform trees versus recursive treesBrowser
import random

rnd = random.Random(0)
n, reps = 30, 4000
hoja1_unif = hoja1_rec = hojaN_rec = 0
for _ in range(reps):
    E = prufer_decodificar([rnd.randint(1, n) for _ in range(n - 2)])        # uniforme
    hoja1_unif += sum(1 in e for e in E) == 1
    R = [(v, rnd.randint(1, v - 1)) for v in range(2, n + 1)]               # recursivo
    hoja1_rec += sum(1 in e for e in R) == 1
    hojaN_rec += sum(n in e for e in R) == 1
print(f"uniforme:  P(1 es hoja) = {hoja1_unif / reps:.3f}   (teoría (1 - 1/n)^(n-2) = {(1 - 1 / n) ** (n - 2):.3f})")
print(f"recursivo: P(1 es hoja) = {hoja1_rec / reps:.3f}   P({n} es hoja) = {hojaN_rec / reps:.3f}")

In a uniform tree all vertices are exchangeable, and each is a leaf with probability ≈0.39\approx 0.39. In a recursive tree, vertex 1 almost never is (it is a leaf only if nobody but 2 attaches to it, with probability 1/(n−1)1/(n - 1)) and the last always is. If you use random trees to test an algorithm, the recursive tree concentrates degree in early vertices and leaves unlike cases untested.

For the matrix-tree theorem, first compare brute force (trying the (mn−1)\binom{m}{n-1} edge subsets) against the nn cofactors, computed with an exact determinant written from scratch. Bareiss elimination is fraction-free Gaussian elimination: after each step, division by the previous pivot is exact, so everything stays in Python integers, which have no size limit.

[ ]Kirchhoff: brute force versus exact determinantBrowser
import numpy as np
from itertools import combinations

def laplaciano(n, aristas):
    L = np.zeros((n, n), dtype=np.int64)
    for u, v in aristas:
        L[u, u] += 1; L[v, v] += 1
        L[u, v] -= 1; L[v, u] -= 1
    return L

def det_bareiss(M):
    """Determinante exacto de una matriz entera (eliminación de Bareiss)."""
    A = [[int(x) for x in fila] for fila in M]
    n, signo, previo = len(A), 1, 1
    for k in range(n - 1):
        if A[k][k] == 0:                                     # pivote nulo: busca otra fila
            p = next((i for i in range(k + 1, n) if A[i][k] != 0), None)
            if p is None:
                return 0
            A[k], A[p] = A[p], A[k]
            signo = -signo
        for i in range(k + 1, n):
            for j in range(k + 1, n):
                A[i][j] = (A[i][j] * A[k][k] - A[i][k] * A[k][j]) // previo   # división exacta
        previo = A[k][k]
    return signo * A[-1][-1] if n else 1

def arboles_fuerza_bruta(n, aristas):
    cuenta = 0
    for S in combinations(aristas, n - 1):
        padre = list(range(n))
        def raiz(x):
            while padre[x] != x:
                x = padre[x]
            return x
        ok = True
        for u, v in S:
            ru, rv = raiz(u), raiz(v)
            if ru == rv:                                     # cierra un ciclo: no es árbol
                ok = False
                break
            padre[ru] = rv
        cuenta += ok
    return cuenta

grafos = {
    "casa": (5, [(0, 1), (0, 2), (1, 2), (1, 3), (2, 4), (3, 4)]),
    "C6 con cuerda": (6, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0), (0, 2)]),
    "K3,3": (6, [(a, b) for a in range(3) for b in range(3, 6)]),
    "K6": (6, list(combinations(range(6), 2))),
    "Petersen": (10, [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)]
                     + [(5 + i, 5 + (i + 2) % 5) for i in range(5)]),
}
for nombre, (n, E) in grafos.items():
    L = laplaciano(n, E)
    cofactores = {det_bareiss(np.delete(np.delete(L, v, 0), v, 1)) for v in range(n)}
    print(f"{nombre:14s} fuerza bruta: {arboles_fuerza_bruta(n, E):5d}   "
          f"cofactores (todos los v): {cofactores}   numpy: {np.linalg.det(L[1:, 1:].astype(float))!r}")

The nn cofactors always agree with brute force. Notice the last column: np.linalg.det returns a float that is almost never an exact integer, and for K3,3K_{3,3} and the Petersen graph it falls below (80.9999999999999680.99999999999996 and 1999.99999999999981999.9999999999998 in the browser; exact figures depend on the linear algebra library). An int() would give 80 and 1999 trees. Now grid graphs of k×kk \times k, where the number of trees grows exponentially in the number of vertices k2k^2:

[ ]Floating point versus exact integersBrowser
from sympy import ZZ
from sympy.polys.matrices import DomainMatrix

def rejilla(k):
    idx = lambda i, j: i * k + j
    E = [(idx(i, j), idx(i, j + 1)) for i in range(k) for j in range(k - 1)]
    E += [(idx(i, j), idx(i + 1, j)) for i in range(k - 1) for j in range(k)]
    return k * k, E

for k in [3, 4, 6, 8, 10]:
    n, E = rejilla(k)
    Lr = laplaciano(n, E)[1:, 1:]
    exacto = det_bareiss(Lr)
    flotante = np.linalg.det(Lr.astype(float))
    simbolico = DomainMatrix([[ZZ(int(x)) for x in fila] for fila in Lr.tolist()], Lr.shape, ZZ).det()
    print(f"{k:2d}x{k:<2d} exacto = {exacto}")
    print(f"       float = {flotante!r}   int(): {int(flotante) == exacto}   "
          f"round(): {round(flotante) == exacto}   sympy: {simbolico == exacto}")

With the 4×44 \times 4 grid, float can already fall just below the integer and int() truncates it incorrectly; from 8×88 \times 8 onward even round() cannot fix it, although relative error is on the order of 10−1410^{-14}: the integer does not fit in the mantissa of a float64. Bareiss and sympy (which works over integers Z\mathbb{Z} with DomainMatrix) give the exact value.

Finally, measure the sorting bound. Class Contador wraps each value and counts calls to <; use it to count insertion-sort and merge-sort comparisons over all permutations of nn elements.

[ ]Actual comparisons versus the log2 n! boundBrowser
import math
from itertools import permutations

class Contador:
    """Un valor que cuenta cuántas veces se le compara."""
    n = 0
    def __init__(self, v):
        self.v = v
    def __lt__(self, otro):
        Contador.n += 1
        return self.v < otro.v

def insercion(a):
    a = list(a)
    for i in range(1, len(a)):
        j = i
        while j > 0 and a[j] < a[j - 1]:
            a[j], a[j - 1] = a[j - 1], a[j]
            j -= 1
    return a

def mezcla(a):
    if len(a) <= 1:
        return list(a)
    m = len(a) // 2
    izq, der = mezcla(a[:m]), mezcla(a[m:])
    out, i, j = [], 0, 0
    while i < len(izq) and j < len(der):
        if der[j] < izq[i]:
            out.append(der[j]); j += 1
        else:
            out.append(izq[i]); i += 1
    return out + izq[i:] + der[j:]

print(" n  ⌈log2 n!⌉  log2 n!  inserción: peor  media   mezcla: peor  media")
for n in range(2, 8):
    res = []
    for orden in (insercion, mezcla):
        cuentas = []
        for p in permutations(range(n)):
            Contador.n = 0
            salida = orden([Contador(x) for x in p])
            assert [c.v for c in salida] == list(range(n))
            cuentas.append(Contador.n)
        res += [max(cuentas), sum(cuentas) / len(cuentas)]
    lg = math.log2(math.factorial(n))
    print(f"{n:2d}  {math.ceil(lg):8d}  {lg:7.2f}  {res[0]:15d}  {res[1]:5.2f}  {res[2]:12d}  {res[3]:5.2f}")

The two worst-case columns never fall below ⌈log⁡2n!⌉\lceil \log_2 n! \rceil, and the averages never fall below log⁡2n!\log_2 n!, as the two theorems require. Merge sort reaches the bound up to n=4n = 4 and is one comparison away for n=5,6,7n = 5, 6, 7; insertion sort, which makes (n2)\binom{n}{2} in the worst case, diverges quadratically.

The library version

networkx functionWhat it doesWatch out for
nx.is_tree(G), nx.is_forest(G)characterization 2 (in each component for a forest)empty graphs raise an exception
nx.from_prufer_sequence(s), nx.to_prufer_sequence(T)the Prüfer bijectionlabels 0,…,n−10, \dots, n - 1, not 1,…,n1, \dots, n
nx.random_labeled_tree(n, seed=...)uniform labeled treeexactly “random sequence and decode”
nx.number_of_spanning_trees(G)matrix-tree theoremreturns a float
nx.SpanningTreeIterator(G)enumerates spanning treesexponential: only for small graphs
nx.minimum_spanning_tree(G)minimum spanning tree (Kruskal by default)studied in m08
nx.nonisomorphic_trees(n)all tree shapes with nn verticesgenerator; grows as 2.956n2.956^n
[ ]networkx versus what we knowBrowser
import networkx as nx
import scipy                 # networkx construye el Laplaciano como matriz dispersa de scipy

# Prüfer con etiquetas 0..n-1: la sucesión (3, 5, 3, 1, 5) es la del ejemplo restando 1
T = nx.from_prufer_sequence([3, 5, 3, 1, 5])
print("aristas:", sorted(T.edges()), "  ¿árbol?", nx.is_tree(T))
print("ida y vuelta:", nx.to_prufer_sequence(T))
print("coincide con lo nuestro:",
      sorted(tuple(sorted((u + 1, v + 1))) for u, v in T.edges())
      == sorted(tuple(sorted(e)) for e in prufer_decodificar([4, 6, 4, 2, 6])))

# formas de árbol: no hay fórmula cerrada
print("árboles no etiquetados, n = 1..10:", [sum(1 for _ in nx.nonisomorphic_trees(n)) for n in range(1, 11)])

# teorema matriz-árbol: un float
for nombre, G in [("casa", nx.house_graph()), ("Petersen", nx.petersen_graph()), ("rejilla 8x8", nx.grid_2d_graph(8, 8))]:
    t = nx.number_of_spanning_trees(G)
    print(f"{nombre:12s} number_of_spanning_trees = {t!r}   int() = {int(t)}")
print("árboles de la casa uno a uno:", sum(1 for _ in nx.SpanningTreeIterator(nx.house_graph())))

The lesson of the last part is the common mistake below: networkx computes τ(G)\tau(G) with np.linalg.det and returns the float as is. If you need an integer, compute the exact determinant.

Common mistakes

Exercises

ProofTwo leaves and n − 1 edges
Prove: Every tree with n≥2n \ge 2 vertices has at least two leaves, and every tree with n≥1n \ge 1 vertices has n−1n - 1 edges.
0
Let TT be a tree with n≥2n \ge 2 vertices and P=v0v1⋯vkP = v_0 v_1 \cdots v_k a maximum-length path in TT (it exists because TT is finite; and k≥1k \ge 1 because TT is connected with at least two vertices).

Step 1 of 4. Why is v0v_0 a leaf?

QuizWhat suffices for a tree?
Let GG be a graph with n≥2n \ge 2 vertices. Which conditions guarantee GG is a tree?

More than one answer may be correct.

QuizWhich traversals determine the tree?
A binary tree has distinct keys. Which pairs of traversals always determine it uniquely?

More than one answer may be correct.

NumericTrees with 6 vertices
How many distinct trees have vertex set {1,2,3,4,5,6}\{1, 2, 3, 4, 5, 6\}? (Two trees are equal if they have the same edges.)
QuizReading a Prüfer sequence
Which tree with vertices {1,…,5}\{1, \dots, 5\} has Prüfer sequence (3,3,4)(3, 3, 4)?
NumericTrees with given degrees
How many trees with vertices {1,…,7}\{1, \dots, 7\} satisfy deg⁡(1)=3\deg(1) = 3, deg⁡(2)=3\deg(2) = 3, deg⁡(3)=2\deg(3) = 2 and have vertices 4,5,6,74, 5, 6, 7 as leaves?
NumericSpanning trees of K₃,₃
How many spanning trees does the complete bipartite graph K3,3K_{3,3} have?
NumericA cycle with a chord
To cycle C6C_6 with vertices 1,2,…,61, 2, \dots, 6 (edges {1,2},{2,3},…,{6,1}\{1,2\}, \{2,3\}, \dots, \{6,1\}), add chord {1,3}\{1, 3\}. How many spanning trees does it have? Try counting without determinants.
NumericA full binary tree
A full binary tree (each node has 0 or 2 children) has 50 leaves. How many nodes does it have in total?
NumericSorting 10 elements
What is the lower bound ⌈log⁡2n!⌉\lceil \log_2 n! \rceil on the worst-case number of comparisons for sorting n=10n = 10 distinct elements?
CodeDecode Prüfer
Implement prufer_decode(seq): it receives a sequence of length n−2n - 2 with values in 1,…,n1, \dots, n (with n≥2n \ge 2) and returns the list of the tree's n−1n - 1 edges as (u, v) pairs in any order. The tests check, for every sequence with n≤7n \le 7, that encoding your tree recovers the sequence.
def prufer_decode(seq):
  """Sucesión de Prüfer (valores 1..n, longitud n - 2) -> lista de aristas (u, v)."""
  n = len(seq) + 2
  aristas = []
  # tu código: en cada paso, une el primer número pendiente con el menor vértice
  # que ya no aparece en lo que queda de la sucesión (y no se ha usado)
  return aristas
Shift+Enter to run
ProofThe decision-tree bound
Prove: A binary tree with LL leaves has height at least ⌈log⁡2L⌉\lceil \log_2 L \rceil, and every comparison-sorting algorithm needs at least ⌈log⁡2n!⌉\lceil \log_2 n! \rceil comparisons in the worst case to sort nn distinct elements.
0
Let TT be a nonempty binary tree with LL leaves and height hh.

Step 1 of 4. Which inequality do you prove first, and how?

Summary

Key idea
A tree is the graph that connects without waste: connected, acyclic, and with n−1n - 1 edges, so any two of those properties imply the third. Almost everything proved about trees comes from removing a leaf, and almost everything counted about them comes from a bijection (Prüfer) or determinant (Kirchhoff).
  • A new edge either joins two components or closes a cycle. Hence m≥n−cm \ge n - c, with equality if and only if the graph is acyclic, and the six tree characterizations.
  • Every tree with n≥2n \ge 2 vertices has two leaves, and removing one leaves a tree: the universal induction step.
  • In a binary tree, n0=n2+1n_0 = n_2 + 1, there are at most 2d2^d nodes at depth dd, and a complete tree has height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor. There are CnC_n binary trees with nn nodes.
  • Preorder plus inorder (or postorder plus inorder) determine a binary tree with distinct keys; preorder plus postorder leave 2k2^k possibilities, with kk the one-child nodes.
  • A graph has a spanning tree if and only if it is connected; the m−n+1m - n + 1 edges outside a spanning tree give a basis of the cycle space.
  • There are nn−2n^{n-2} labeled trees: Prüfer code is a bijection in which each vertex appears deg⁡−1\deg - 1 times.
  • The number of spanning trees is any diagonal cofactor of L=D−A\mat{L} = \mat{D} - \mat{A}; it is computed in O(n3)\bigO(n^3), but with exact arithmetic.
  • A binary tree with LL leaves has height at least ⌈log⁡2L⌉\lceil \log_2 L \rceil and mean depth at least log⁡2L\log_2 L; therefore comparison sorting costs at least ⌈log⁡2n!⌉≈nlog⁡2n−1.44 n\lceil \log_2 n! \rceil \approx n\log_2 n - 1.44\,n.