Pre-order works before the children, post-order after them
Where the work sits next to the calls on the children decides what each region knows.
def walk(region, depth, pre, post): # pre-order: before the children pre.append((region, depth)) for child in children[region]: walk(child, depth + 1, pre, post) # post-order: after them post.append(region)pre, post = [], []walk("Europe", 0, pre, post)print(f"{'pre, with depth':<24}post")for (region, depth), finished in zip(pre, post): print(f"{region + ' ' + str(depth):<24}{finished}")
Predict
post records a region after all its children. Which region comes first in post-order?
Pick one to see what it prints.
The two columns are two separate lists. Each region's place in both, on Portugal's subtree:
Each region's place in pre-order and post-order
Portugalafter all 6 regions inside it
pre 1, post 7
Lisbon District
pre 2, post 4
Lisbonthe leaves come first
pre 3, post 1
Sintra
pre 4, post 2
Cascais
pre 5, post 3
Porto District
pre 6, post 6
Porto
pre 7, post 5
Where the work sits next to the calls on the children has a name:
Pre-order: the region, then its children. Information flows down. Depth is the example: a region's depth is its parent's depth plus 1, so it's known before the children are visited, and you pass it in as an argument.
Post-order: the children, then the region. Information flows up. Size, height and totals are post-order, because each needs the children's answers.
In post-order every region comes after everything inside it. So by the time you reach a region, its children's answers are ready. Remember that line: it comes back when you walk with a stack of your own.
In the editor, write depths(children, top), pre-order work that passes the depth down. It prints a few depths, and how many regions got one.
Pick an answer above to see the rest
Instructions
1
Write depths(children, top) with recursion: a dict from every region to its depth, with the top at 0.
2
Pass the depth down: a region's depth is known before its children are visited, so this is pre-order work.