Code

The same traversal, twice

Create walk.go (see the panel). It holds Folder, the two traversals and two tree-building helpers.

Read the two traversals side by side. WalkRecursive is four lines. WalkIterative is ten, and eight of them are managing the stack slice.

Those eight lines are what the runtime does for you in the recursive version.

One thing that is easy to miss

// Push children in reverse so they come off in the original order.
for i := len(f.Subs) - 1; i >= 0; i-- {
    stack = append(stack, f.Subs[i])
}

A stack is last-in-first-out. Push the children in order and they come out backwards. You never see this in the recursive version, because the loop order decides it for you.

When the stack becomes yours, the order becomes your responsibility. That is a cost — and also an opening: in lesson 14 you swap the stack for a queue and get an entirely different traversal order.

The result

$ algo walk -depth 3 -branch 3 -per 2
tree: depth=3 branch=3 items-per-folder=2

walk                          items folders visited
recursive                        80             40
iterative (your stack)           80             40

identical — same algorithm, different place to keep the stack

The same 80 items, the same 40 folders. Not similar — identical.

That is the point of the lesson: recursion and a loop with a stack are two ways of writing down the same algorithm. Not two algorithms.