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) * 3into 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 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 nodes always has edges, a vector padre of length represents it entirely, and checking whether an input is a tree costs . If there are exactly 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 leaves has height at least , no comparison-sorting algorithm can go below roughly 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.
Three things the figure shows, which the next section turns into theorems:
- 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.
- The “exactly two” cells do not light up. However you try, connected and acyclic requires edges; connected with edges requires no cycles; and acyclic with edges requires connectedness. Any two imply the third.
- The number is never negative, and is 0 exactly when there are no cycles. The “Trap” has edges and is not a tree: it has two triangles and an isolated vertex, so .
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 vertices, edges, and 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 using contains a path from to that does not use , that is, a path in . If and 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 from to in , and plus edge is a cycle; the components do not change because and were already connected.
∎Proof
Construct by adding its edges one at a time to the edgeless graph, which has components. By the preceding lemma, each edge either decreases by one or closes a cycle without changing . If edges close a cycle, at the end , that is, . If is acyclic, no edge closed a cycle when added (that cycle would still be in ), so . Conversely, if has a cycle , the last edge of to be added joined two vertices already connected by the rest of and closed a cycle, so .
∎The number 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 , with equality if and only if is acyclic.
1, 2 and 3. If 1 holds, and , so : 2 and 3 hold. If 2 holds, , so is acyclic. If 3 holds, because it is acyclic and , so .
1 and 4. If is a tree, at least one path joins each pair because it is connected. If there were two distinct paths and from to , let be the last vertex of their shared initial segment (the vertex after which they first separate), and let be the first vertex of after that also lies in (it exists because does). The segments of and between and have no interior vertices in common, so together they form a cycle: contradiction. Conversely, if exactly one path joins each pair, 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 is a tree and remained connected after removing edge , there would be a path from to without that edge, which together with it would form a cycle. Conversely, if 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 is a tree, and are in the same component and, by the first lemma, has a cycle. Conversely, if 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 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 (free) and connectivity (one traversal, because you already know ). 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 . And “leaf” changes meaning upon rooting: the root of a path 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 , entries. Such a vector represents a rooted tree if and only if following parents from any vertex reaches 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 binary trees with nodes, the Catalan numbers : the recurrence chooses the size 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 edges, with . Each node has as many downward edges as children: there are . Equating gives , that is, . In a full tree and .
∎The same equality follows by structural induction (in tree 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 leaves has exactly splits. In an elimination tournament with participants, each match eliminates one: matches.
Proof
By induction on : level 0 is the root, and each node at level contributes at most two to level . Summing gives , hence and, since it is an integer, . A complete tree of height has full levels and at least one node at : , that is, .
∎The complete tree has minimum height and is stored in an array without pointers: with indices starting at 1, the children of node are and , and its parent is . 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 . Postorder visits a node after its subtree: it is the evaluation order (operands before the operation, as in reverse Polish notation 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 with left child and the tree rooted at with right child have the same inorder, ; and root with a single child gives the same preorder, , whether hangs on the left or right. What about two traversals?
Proof
Use strong induction on the number of nodes . With the tree is empty. Let and let be any tree with preorder and inorder . The root must be , the first element of preorder. Since keys are distinct, appears exactly once in , say at position . By the definition of inorder, and , so has nodes. By the definition of preorder, and . All of this is fixed by and , with no choice. By the induction hypothesis, is determined by and by , hence so is . 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 per call and 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 . You will implement it below.
With preorder and postorder the argument breaks at exactly one point. The root is (with the postorder), and if the second element of preorder, , is the root of the first nonempty subtree. In postorder, is last in that subtree, so everything in up to is that subtree. If that is all that remains, the root has one child… and nothing in or says whether it is left or right.
Proof
Use strong induction on , following the previous argument. If there is one tree and . If , let and let be its position in . If , the root has two children: the first subtree consists of and the second of , the corresponding preorder segments are fixed, and the number of trees is the product by induction. If , the root has one child, whose subtree has preorder and postorder ; it can hang left or right, and the count is , with the root counted among one-child nodes. The number is determined by and 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 is a spanning tree, every pair of vertices is joined by a path in , which also lies in . Conversely, if 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 of a connected graph . There are edges outside , and each, , closes with the unique path from to in a cycle , the fundamental cycle of . Also, if you remove any edge from , is another spanning tree (connected with edges): this is the exchange property used to prove Kruskal correct.
Why was the cyclomatic number called “independent cycles”? Represent each edge set by its indicator vector in 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 : the modulo-2 sum of two still has all degrees even. This is the cycle space.
Proof
Independent: each contains exactly one edge outside , its own; in any sum of several, edge of each summand appears only in that summand and does not cancel. Spanning: let be an even-degree subgraph and let . Each edge outside appears in an even number of times (once in and once in its ), so , and has even degrees. But a nonempty subgraph of is a forest with an edge, and a component with edges is a tree with at least two leaves, of degree 1. Thus and .
∎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 , 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 ? Here vertices are named: two trees are equal if they have exactly the same edges, even if they have the same shape. With there are 3 (the central vertex is 1, 2, or 3). With there are two shapes, the path and the star: paths (an ordering of vertices up to reversal) and 4 stars (choice of center), 16 total. With 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 is .
Notice the contrast: with 6 vertices there are only 6 tree shapes, but labeled trees. And is the number of sequences of length with values in , 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 : while is in the tree, whenever a neighbor (which was a leaf) is removed, is recorded. Vertex 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 neighbors and has been recorded once for each.
∎Proof
Use induction on , over arbitrary vertex sets of numbers (the algorithm only uses label order). For there is one tree and one sequence, the empty one. Let and let be any sequence over a set of labels. Call the smallest element of absent from (it exists because has terms and has elements).
At most one tree has code . If has code , by the lemma its leaves are the elements of absent from , so the first leaf removed is , its neighbor is , and is a tree on with code , because the algorithm on continues exactly as on . By the induction hypothesis is determined, and so is .
At least one tree has code . The sequence does not contain , so by hypothesis there is a tree on with that code. Let , which is a tree because a leaf is added. By the lemma applied to , its leaves are the elements of absent from ; in , gains a neighbor, so the leaves of are and the elements of absent from . The smallest is , removed first while recording , and the rest of the algorithm is that of . The code of is .
∎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.
The degree lemma gives more than the total count. A tree with prescribed degrees (with , all ) corresponds to a sequence in which each appears times, and such sequences are counted by a multinomial coefficient:
Summing over all degrees recovers by the multinomial theorem. Other immediate consequences: there are 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 . To generate a tree uniformly at random, simply generate a uniform sequence and decode it. The naive method of attaching each vertex to a randomly chosen earlier vertex produces the random recursive tree, which is not uniform: with vertex 3 is never the center and the other two are each the center with probability , instead of .
The matrix-tree theorem
Cayley counts spanning trees of the complete graph . What about an arbitrary graph? Kirchhoff’s answer is a determinant.
Three properties are apparent. is symmetric. Every row sums to 0, so and : that is why a row and column must be removed. And factors. Orient each edge arbitrarily and form the incidence matrix , whose column for edge from to has in row , in row , and zeros elsewhere. Then
because counts columns with a in row (the degree) and if 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.
The proof combines three pieces: the factorization , the Cauchy–Binet formula, and a lemma translating “being a tree” into the language of determinants.
Cauchy–Binet. If is and is with , then , where ranges over subsets of columns of (the same rows of ). If , the rank of is less than and the determinant is 0. This generalizes to rectangular matrices.
Proof
If is not a tree, since it has edges, characterization 2 says it is disconnected. Let be a component not containing . Sum the rows of corresponding to vertices of : every edge of has both endpoints in (contributing ) or neither (contributing 0), because no edge leaves a component. The rows are dependent and the determinant is 0.
If is a tree, use induction on . With , and the matrix is , with determinant 1. With , the tree has at least two leaves, so a leaf differs from . The row of in has one nonzero entry, , in the column of the unique edge of . Expanding along that row (cofactor expansion), , where is the matrix without row or column : exactly the incidence matrix, without the row of , of tree on vertices. By the induction hypothesis, .
∎Proof
(Of the theorem.) Removing row and column from means removing row from and column from : . By Cauchy–Binet with ,
By the lemma, each term is 1 if is a spanning tree and 0 otherwise. The sum counts spanning trees. If 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 depends on the chosen orientation, but it is squared.
Three useful extensions. If every edge has weight and the Laplacian is weighted (, ), the same argument gives , 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, , the product of the nonzero eigenvalues of divided by .
Decision trees and the sorting bound
A comparison-based sorting algorithm can obtain information about its input only by asking “is ?” For fixed size , 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, , by structural induction: a leaf has , and a node whose subtrees have height has at most leaves; since is an integer, . Second, each of the 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 ? From follows , and Stirling’s formula sharpens it: . No comparison sort goes below in the worst case: mergesort, which makes at most , is optimal up to a linear term. This is the comparison-sorting lower bound, revisited in m08.
| 4 | 5 | 8 | 10 | 12 | |
|---|---|---|---|---|---|
| 5 | 7 | 16 | 22 | 29 | |
| mergesort, worst case | 5 | 8 | 17 | 25 | 33 |
| merge-insertion (Ford–Johnson) | 5 | 7 | 16 | 22 | 30 |
The bound is not always attained: for exhaustive search shows (Wells, 1965) that 30 comparisons are needed, one more than says. The clearest way to see why the bound is unavoidable is to play against an adversary.
The adversary is the proof as a game: if 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 . There is also an information interpretation: identifying one permutation among requires 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 leaves is at least .
Proof
Kraft’s inequality follows by structural induction: a single leaf contributes ; if the root has subtrees and (perhaps) , each leaf is one level lower than in its subtree, so the sum is . For the mean, the function is convex, and by Jensen’s inequality , where is the mean. Taking logarithms gives .
∎Thus even averaged over the equiprobable inputs, a comparison sort makes at least 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 up to , check that any two of the three properties imply the third and, up to , that the unique-path characterization agrees. As a bonus, the number of trees among those graphs matches Cayley’s formula.
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 . Next come traversals and reconstruction in . A tree is a triple (clave, izq, der) or None. To check the theorem, generate all binary-tree shapes with nodes (giving Catalan numbers) and label them in preorder, so preorder is always and two trees share preorder and postorder if and only if they share postorder.
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 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.
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 , so they cost ; the direct version searching for the minimum at every step costs . The bijection is checked by complete enumeration up to : each of the sequences gives a valid tree, encoding it recovers the sequence, the degree lemma holds, and all resulting trees are distinct.
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 edges that encodes back to it, decoding is injective, and distinct trees arise from 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:
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 . In a recursive tree, vertex 1 almost never is (it is a leaf only if nobody but 2 attaches to it, with probability ) 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 edge subsets) against the 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.
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 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 and the Petersen graph it falls below ( and in the browser; exact figures depend on the linear algebra library). An int() would give 80 and 1999 trees. Now grid graphs of , where the number of trees grows exponentially in the number of vertices :
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 grid, float can already fall just below the integer and int() truncates it incorrectly; from onward even round() cannot fix it, although relative error is on the order of : the integer does not fit in the mantissa of a float64. Bareiss and sympy (which works over integers 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 elements.
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 , and the averages never fall below , as the two theorems require. Merge sort reaches the bound up to and is one comparison away for ; insertion sort, which makes in the worst case, diverges quadratically.
The library version
| networkx function | What it does | Watch 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 bijection | labels , not |
nx.random_labeled_tree(n, seed=...) | uniform labeled tree | exactly “random sequence and decode” |
nx.number_of_spanning_trees(G) | matrix-tree theorem | returns a float |
nx.SpanningTreeIterator(G) | enumerates spanning trees | exponential: 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 vertices | generator; grows as |
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 with np.linalg.det and returns the float as is. If you need an integer, compute the exact determinant.
Common mistakes
Exercises
Step 1 of 4. Why is a leaf?
More than one answer may be correct.
More than one answer may be correct.
prufer_decode(seq): it receives a sequence of length with values in (with ) and returns the list of the tree's edges as (u, v) pairs in any order. The tests check, for every sequence with , 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 aristasStep 1 of 4. Which inequality do you prove first, and how?
Summary
- A new edge either joins two components or closes a cycle. Hence , with equality if and only if the graph is acyclic, and the six tree characterizations.
- Every tree with vertices has two leaves, and removing one leaves a tree: the universal induction step.
- In a binary tree, , there are at most nodes at depth , and a complete tree has height . There are binary trees with nodes.
- Preorder plus inorder (or postorder plus inorder) determine a binary tree with distinct keys; preorder plus postorder leave possibilities, with the one-child nodes.
- A graph has a spanning tree if and only if it is connected; the edges outside a spanning tree give a basis of the cycle space.
- There are labeled trees: Prüfer code is a bijection in which each vertex appears times.
- The number of spanning trees is any diagonal cofactor of ; it is computed in , but with exact arithmetic.
- A binary tree with leaves has height at least and mean depth at least ; therefore comparison sorting costs at least .