Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Unroll and roll back

โญโญโญ advancedโณ 10 min read๐Ÿ“ Lesson 197 of 256

Single-branch chains unroll to the base and roll back one value per level; parity-switching branches get annotated.

Recursive tracing is bookkeeping, not magic. For a single-branch call chain (f(n) = f(n-1) + n), unroll downward to the base, then roll back up, writing one value per level:

public static int f(int n) {
    if (n <= 0) { return 1; }
    return f(n - 1) + n;
}
// f(4): f(3)+4 ... f(0)=1 โ†’ 1+1=2 โ†’ 2+2=4 โ†’ 4+3=7 โ†’ 7+4=11

The two errors students make: stopping the roll-up one level early (off-by-one from base to first addition), and misreading the base case's value (1 vs 0 changes everything โ€” trace it, don't assume).

For two-branch recursion (mystery(n-1) + 2 vs mystery(n-1) * 2 chosen by parity), the chain is still linear here โ€” only ONE branch runs per call โ€” but the branch switches as n changes. Draw the chain with the branch decision at each level:

// mystery(5): odd โ†’ mystery(4)*2; mystery(4): even โ†’ mystery(3)+2;
// mystery(3): odd โ†’ mystery(2)*2; mystery(2): even โ†’ mystery(1)+2;
// mystery(1): odd โ†’ mystery(0)*2; mystery(0) = 0
// roll up: 0*2=0 โ†’ 0+2=2 โ†’ 2*2=4 โ†’ 4+2=6 โ†’ 6*2=12