13/38
Part 3 of 7 · Your own stackLearn and do

Read the popping order backwards, and every region comes after everything inside it

Post-order work, like sizes, needs every child finished first. A stack pops the parent before any child. The trick is to record the order in which regions come off the stack:

def sizes_with_stack(children, top):
    order, stack = [], [top]
    while stack:
        region = stack.pop()
        # each region lands after the one containing it
        order.append(region)
        stack.extend(children[region])
    sizes = {}
    # backwards: each region after everything inside it
    for region in reversed(order):
        total = 1
        for child in children[region]:
            total += sizes[child]
        sizes[region] = total
    return sizes


for region, n in sizes_with_stack(children, "Portugal").items():
    print(region, n)
Lisbon 1
Sintra 1
Cascais 1
Lisbon District 4
Porto 1
Porto District 2
Portugal 7

Every region is pushed by its parent, so it comes off after its parent. Read backwards, that order puts every region after everything inside it:

Order, as poppedSize, filled in from the bottom up
Portugal7 = 1 + 4 + 2, last
Porto District2 = 1 + 1
Porto1
Lisbon District4 = 1 + 1 + 1 + 1
Cascais1
Sintra1
Lisbon1, start here

By the time the backwards pass reaches a region, each of its children already has a size. The printed order, Lisbon to Portugal, is exactly the post-order the recursive walk gave. That holds on any tree: the popping order, read backwards, is post-order.

In the editor, write totals_with_stack(children, own, top). It totals three regions' listings up the Europe tree.