33/38
Part 7 of 7 · Follow-upsLearn

When the tree is too big for memory, start at the leaves and release a parent when its last child reports

Keep the tree as (child, parent) rows in a database or in files. Totals still come from the bottom up, and a release-when-ready loop gets them without knowing any depths:

  1. Count each node's children.
  2. Start from the leaves.
  3. When a node's last child has reported, add the node's total into its parent's, and release the parent.

The topological sort lesson builds the same loop. With the counts and totals in a key-value store, only the nodes ready to report sit in memory. A database can do the same walk in one recursive query (WITH RECURSIVE). For a deep but not huge tree, your own stack is the whole fix.