2/27
Part 1 of 7 · Messages instead of callsLearn and do

On one machine, the count is a recursion

If you could see the whole tree, you would count it with a recursion. A tree is a dict from each machine to the list of its children. The count under a machine is 1 for itself plus the count under each child.

# id -> children
TREE = {0: [1, 2], 1: [3, 4], 2: [], 3: [], 4: []}

def size(tree: dict[int, list[int]], node: int) -> int:
    """The number of machines under node, node included."""
    return 1 + sum(size(tree, child) for child in tree[node])

print(size(TREE, 0), size(TREE, 1), size(TREE, 4))
5 3 1

Watch what each call does. It asks each child for a number, waits for all of them, adds 1 and hands the total back to whoever called it. The calls go down the tree and the totals come back up:

size(TREE, 0), call by call
0returns 1 + 3 + 1 = 5, last of all
1returns 1 + 1 + 1 = 3
3returns 1
4returns 1
2returns 1

That is the whole protocol, before any network. The call going down becomes a message, an ask. The value coming back becomes another message, an answer. Everything after this handles what a network does to those two messages: it delays them, reorders them, loses them and repeats them.

One more number matters later: the depth of the tree, the links on the longest path from the root down to a machine with no children. Every ask has to travel down that path and every answer back up it, so the depth sets how long a count takes.

The editor holds TREE and the size above. Write depth(tree, node) by recursion: it takes the deepest child, never the sum of the children.