Pre + Post + Inorder in One Traversal
Produce preorder, inorder and postorder lists in a single traversal.
Open on GeeksforGeeks ↗Intuition
Each node is visited exactly three times during a DFS: on arrival (pre), between children (in), after children (post). Push (node, state) on a stack; each pop records the node in one list, bumps its state, and schedules the next child.
One stack carrying (node, state) pairs simulates the three points a recursive call passes through each node: before the left call, between the calls, and after the right call. Emitting at state 1, 2, 3 gives preorder, inorder, and postorder from a single pass — this is literally what the call stack does, made explicit.
Approach
State 1, 2, 3
State 1: record preorder, push left. State 2: record inorder, push right. State 3: record postorder, done.
Re-push with incremented state
Pop (node, s); if s < 3 re-push (node, s+1) before pushing the child — the node re-surfaces after that child's subtree completes.
One pass, three answers
Every node cycles through the three states exactly once → O(n) total.
Solution & live demo
Common pitfalls
Not re-pushing the node with its next state
if state == 1:
pre.append(node.val)
if node.left: stack.append((node.left, 1))if state == 1:
pre.append(node.val)
stack.append((node, 2))
if node.left: stack.append((node.left, 1))The node must be revisited twice more, once after the left subtree and once after the right. Dropping the re-push means inorder and postorder never receive it.
Pushing the child before the node's next state
stack.append((node.left, 1)) stack.append((node, 2))
stack.append((node, 2)) if node.left: stack.append((node.left, 1))
A stack pops in reverse, so the child must be pushed last to be processed first. Reversing the order visits the node's state-2 step before its left subtree, scrambling the inorder output.
Running three separate traversals
return preorder(root), inorder(root), postorder(root)
stack = [(root, 1)]
Three passes is three times the tree walking, and the point of the exercise is seeing that all three orders are the same walk sampled at different moments. One pass makes that relationship visible.
Edge cases
Stack depth reaches n — same as recursion would.
All three lists empty.