Where the work happens

Move one line and the answer arrives from the other end.

Four recursions with the same skeleton. The only thing that changes is whether the work sits before the recursive call or after it.

Call stack

Output

 

Press Next to make the first call.

func

The same skeleton, twice

Compare print 1..N and print N..1. The calls happen in the same order both times, and the stack grows identically. What differs is when each frame does its job.

Work before the call fires as the stack grows, so the largest argument acts first and you get N..1. Work after the call waits for every deeper frame to finish, so the smallest acts first and you get 1..N. Nothing is reversed and no array is used: the call stack holds the order, and unwinding plays it back.

A recursive function has two places to put work. Choosing between them is most of what recursion design is.

Why factorial and sum of digits are here

They use the same skeleton with a returned value instead of a print. Watch the stack build to a base case that does nothing, then watch the value assemble on the way back up: 1, then 2, 6, 24.

It is also why the base case must be the identity of the operation that combines: 1 for multiplication, 0 for addition. Get it wrong and the recursion still terminates, but every value above it is wrong.

Where this goes

Pre-order and post-order are the names for these two halves, and they keep coming back: tree traversals in Week 2, LC 206 rewiring links on the way back up, LC 21 choosing heads on the way down. Every DP recurrence is post-order: solve the smaller thing, then combine.