Count the Nodes of a Tree by Messages
Every node of a tree is a separate machine that can message only its neighbours, asynchronously. Write the per-node logic as a class TreeNode(id, neighbors, send), where send(from, to, kind, requestId, count) delivers a message later — possibly out of order, possibly twice. Two message kinds exist: "REQUEST" and "REPLY".
startCount(requestId)begins a count at this node.receive(sender, kind, requestId, count)is called for every delivered message.- When the count completes, the node that started it sets
this.resultto the number of nodes in the tree.
The grader runs the simulation with a scrambled delivery order and duplicated messages and reads result on the starting node.
Hints
Hint 1
On a request, ask every neighbour except the sender and remember who you are waiting for; a leaf replies at once with 1. When the last awaited reply arrives, reply to whoever asked you with 1 plus the sum.
Hint 2
Duplicates: ignore a reply from a neighbour you are no longer waiting for; ignore a repeated request while you are working on it; answer a repeated request again from a cache once you have finished.