Watch: frames in, frames out
There is no code here yet. What is here is what the call stack does when you walk the library's folders — on the same small tree from step 1, now with the number of items in each folder.
You write nothing in this step. In the next step you will find two traversals, and you will recognise both from these tables.
root (0 items)
├── rokas (2)
│ ├── 90-ieji (3)
│ └── klasika (1)
└── džiazas (2)
└── bebopas (4)
How we count
Two numbers per row:
- depth — how many
WalkRecursiveframes are alive on the call stack after this event; - folders visited — the same counter you will see in the code as
c.Hit(): once per folder, when it is entered.
Recursive walk: a frame goes in, a frame comes out
→ means "call entered", ← means "call returned" with the number of items it
found.
event depth folders visited
1 → root 1 1
2 → rokas 2 2
3 → 90-ieji 3 3
4 ← 90-ieji returns 3 2
5 → klasika 3 4
6 ← klasika returns 1 2
7 ← rokas returns 6 1 (2 own + 3 + 1)
8 → džiazas 2 5
9 → bebopas 3 6
10 ← bebopas returns 4 2
11 ← džiazas returns 6 1 (2 own + 4)
12 ← root returns 12 0 (0 own + 6 + 6)
While rows 3–6 run, the rokas frame has not gone away: it waits on the
stack holding its local n = 2 until its children return and add to it.
The same walk with your own stack
Now a loop and a []*Folder do the same job. The top is on the right.
stack before the pop pop items so far folders visited
[root] root 0 1
[džiazas rokas] rokas 2 2
[džiazas klasika 90-ieji] 90-ieji 5 3
[džiazas klasika] klasika 6 4
[džiazas] džiazas 8 5
[bebopas] bebopas 12 6
When it pops root, the loop pushes its children in reverse order
(džiazas, then rokas) so that rokas ends up on top and comes off first.
Three observations
1. The folder order is the same: root, rokas, 90-ieji, klasika, džiazas, bebopas. Both walks visit 6 folders and find 12 items. That is not a
coincidence: it is one algorithm written twice.
2. The two stacks hold different things. The call stack holds the way
back: the folders you descended through and must return to
(root → rokas → 90-ieji). Your stack holds work not yet done: folders you
have not visited (džiazas, klasika, 90-ieji). On this tree both reach depth 3,
but that is a coincidence of this small tree.
3. In recursion the answer builds up on the way back. No frame knows the
total until its children have returned: rokas learns its 6 only in row 7, and the
final 12 comes in the last row. In the loop the sum grows going forward,
one pop at a time.
What next
In the next step you write both walks as Go code and run them on a bigger tree — the numbers must match.