Skip to content
BytePatterns

The Decision Tree

Backtracking: lesson 1 of 5

Choose, explore, un-choose — one shared path walks the whole tree.

Lesson 1 of 5 · 5 min

The Decision Tree

Step 1 of 8

Every backtracking problem is this tree. The root is the empty path; each level picks one more letter.

The Idea

Backtracking is depth-first search over a tree you never build. Each node is a partial answer, each edge is one choice, and each leaf is a finished candidate.

The loop is always the same three moves: push a choice onto the path, recurse to extend it, then pop it off. That pop is the whole trick — it restores the path so the next option starts from exactly the same state, which is why one list can serve the entire search.

Real-World Example

Trying keys on a ring of unlabelled keys in a building with several locked doors. You take a key, walk deeper, and when a door refuses you put that key back before trying the next one — otherwise the ring is wrong for every attempt after.

The Code

def walk(options, path, out):
    if len(path) == 2:               # the decision sequence is complete
        out.append("".join(path))
        return
    for opt in options:
        path.append(opt)             # choose
        walk(options, path, out)     # explore
        path.pop()                   # un-choose

out = []
walk(["a", "b"], [], out)
print(out)

Python

Your turn

What does this print?

out = []
walk(["a", "b"], [], out)
print(out)

Mini quiz

1 / 3

What are the three moves of every backtracking loop?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.