Tracing Preorder and Postorder Tree Visits
The position of a node's action relative to its children determines whether the traversal processes parents before or after descendants.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Walk a three-node fork
For a root R with ordered leaf children A then B, preorder emits R, A, B. Postorder emits A, B, R. Recursive call tracing can mark the print at entry or at return to produce either result.
Choose by dependency
Building a textual path from a parent can use information available at entry. Gathering a directory size needs the children's totals before computing the parent's. That calculation follows recursively counting descendants, even when each child contributes a nonunit weight.[1]
Put a visit before or after child traversal
Use a root A whose ordered children are B and C. B has children D and E. Record the root when you enter its frame for preorder, or when you leave the last child for postorder. Children retain their chosen order under either policy. See nested call traces.
Enter/exit: enter A, enter B, enter D, exit D, enter E, exit E, exit B, enter C, exit C, exit A
Preorder: A B D E C
Postorder: D E B C A
Pick order from what a visit requires
To compute child sizes before a parent's size, postorder places the required values first. To emit each heading before its nested headings, preorder puts parent context first. Test a node with two children so the expected trace also fixes the sibling order.