Replacing Recursion with an Explicit Worklist

An explicit worklist stores pending tasks in ordinary data structures. Its ordering governs which task the traversal performs next.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Simulate a traversal stack
  2. Retain return actions when needed
  3. Preserve the order in which pending nodes are taken
  4. Retain a continuation when results flow back upward

Simulate a traversal stack

For a root with left and right children, pushing right and then left causes left to be popped first. That preserves the order of a left-first preorder recursion. Stack and queue order explains why a queue gives a different traversal.

Retain return actions when needed

Postorder may require a marker saying a node's children were scheduled and its final action remains. Add the marker and the children in an order consistent with the stack. Preorder and postorder help check the result on one fork.[1]

Preserve the order in which pending nodes are taken

A recursive preorder walk of A with children B and C enters B before C. With a stack, push them in reverse order so B is popped next. For a state graph, carry whatever fields a recursive frame would have used to distinguish visits. See preorder and postorder traces.

Pending stack, top at right
[A] → pop A, push C then B → [C, B]
Pop B, push child D → [C, D]
Pop D → [C] → pop C
Visit order: A B D C

Retain a continuation when results flow back upward

An algorithm summing child results after exploring them needs more than a pending node ID. Store a frame with the next child index and partial sum, or push a separate completion event. Test a branching tree whose answer uses both child results.

References

  1. Jeff Erickson, Algorithms ↩