Sub topic 2
Thinking in State-Space Trees
This chapter assumes you can write recursive functions with base cases, read Python tuples and lists, and follow Big-O notation. It builds on the previous chapter's picture of the call stack.
The Core Idea
Backtracking problems ask you to build an answer one decision at a time: pick the next element, place the next queen, fill the next cell. A state-space tree draws every possible sequence of those decisions.
| Tree part | Meaning in the search |
|---|---|
| Root | The empty partial solution, before any choice |
| Edge | One choice that extends a partial solution |
| Node | A partial solution, meaning the choices made so far |
| Depth | How many choices have been made |
| Leaf | A complete candidate, or a dead end where no choice is valid |
Backtracking is a depth-first walk over this tree. The search goes down one branch until it reaches a leaf or a dead end. Then it returns to the nearest node that still has untried choices. Each recursive call is one node, and the call stack holds the path from the root to that node.
Permutations as a Tree
To build a permutation of [1, 2, 3], you choose the first number, then the second from what remains, then the last.
The branching factor shrinks with depth. The root has 3 children, the nodes at depth 1 have 2 each, and the nodes at depth 2 have 1 each. The tree has 3! = 6 leaves, and the total node count is 1 + 3 + 6 + 6 = 16. Counting nodes like this is the basis of the cost analysis later in the tutorial.
Same Problem, Different Tree
How you define a "choice" decides the shape of the tree. For subsets, one option is to ask, for each element in order, "include it or not?" That gives a binary tree in which every leaf is one subset. The walker below prints that tree. It passes immutable tuples, so this example has no state to undo.
def walk(items, i, partial):
indent = " " * i
if i == len(items):
print(indent + "leaf:", partial)
return
print(indent + "node:", partial)
walk(items, i + 1, partial + (items[i],)) # include items[i]
walk(items, i + 1, partial) # exclude items[i]
walk(('a', 'b'), 0, ())Output:
node: ()
node: ('a',)
leaf: ('a', 'b')
leaf: ('a',)
node: ()
leaf: ('b',)
leaf: ()The indentation is the depth, and the depth equals the length of the call stack. A list of n items produces a tree of depth n with 2^n leaves.
Dead Ends
Many problems have constraints, such as "no two queens attack each other" or "the sum must not exceed the target." A node that already breaks a constraint can never lead to a valid leaf. The search can stop at that node and skip its whole subtree. This is the motivation for pruning, which a later chapter covers. For now, keep the full tree in mind as the worst case the search might explore.
Common Errors
- Mixing two tree designs in one function, for example using include/exclude while also looping over later elements. This produces duplicate results.
- Recording results at the wrong nodes. Subsets need every leaf of the include/exclude tree, while permutations need only the nodes at depth n.
- Forgetting that the recursion depth equals the tree depth. Python's default recursion limit is about 1000.
Exercise
How many nodes, including the root, are in the state-space tree for permutations of 4 distinct elements?
Show answer
1 + 4 + 4·3 + 4·3·2 + 4·3·2·1 = 1 + 4 + 12 + 24 + 24 = 65 nodes.
Exercise
In the include/exclude tree for a list of 5 items, how many leaves are there, and what is the maximum call-stack depth below the initial call?
Show answer
There are 2^5 = 32 leaves, one per subset. The tree depth, and so the maximum number of nested calls below the root call, is 5.