Order once, sweep twice
transcript
Total the spend of every team. The teams form a chain. It is a hundred thousand teams deep. Can you total every branch in time?
Walk each branch on its own. On a chain that is five billion steps. A judge runs about a hundred million a second. And Python stops at one thousand nested calls.
List the nodes from the root outwards. Every team follows its boss in the list. Build this list one time only.
Start at the last team in the list. It has nobody below it. Add its total to its boss. Move one step back and repeat. Each team is complete when reached.
Totals come from below. Go backwards. Distances come from above. Go forwards. A loop has no depth limit, so a chain is safe.
Build the order once. Sweep the list, not the tree. Backwards for totals, forwards for distances. Choose the direction first. Then write one short loop. Full breakdown in the lecture.