Binary Tree · DFS
Pre, In & Post Order in One Traversal
Compute all three DFS traversals simultaneously in a single pass using an explicit stack and a visit-count per node.
Key concepts at a glance — for those who already know the basics.
Problem Statement
Preorder, Inorder and Postorder in Single Traversal
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: pre=[1,2,4,5,3,6,7], in=[4,2,5,1,6,3,7], post=[4,5,2,6,7,3,1]
Constraints
- The number of nodes is in range [0, 10^5].
- Node values may be negative and repeated; traversal order must remain deterministic.
01 · The core idea
Every node is visited exactly 3 times. The state counter decides what to do on each visit.
Normally, these need 3 separate DFS passes. This algorithm does all three in one pass.
02 · The three traversals compared
Preorder
[1, 2, 4, 5, 3, 6, 7]
Inorder
[4, 2, 5, 1, 6, 3, 7]
Postorder
[4, 5, 2, 6, 7, 3, 1]
03 · Algorithm steps
Push (root, state=1) onto the stack
Each stack frame is a (node, count) pair.
Pop top frame. Check the state counter.
Increment counter and push the frame back before doing any child push.
State 1 → add to pre[], push left child (state=1)
State 2 → add to in[], push right child (state=1)
State 3 → add to post[], do not push back
Node is fully processed. Naturally falls off the stack.
04 · Code
05 · Complexity
Time
O(n)
Each node is pushed/popped exactly 3 times. Total operations = 3n.
Space
O(n)
Stack holds at most O(h) frames at once. Output arrays together hold 3n values.
06 · Interview uses
Optimize multiple traversal calls
— when a problem requires more than one traversal result, this avoids repeated tree walks.
Iterative DFS mastery
— demonstrates deep understanding of the call stack and how recursion works under the hood.
Tree reconstruction
— preorder + inorder together uniquely identify a binary tree. Getting both in one pass is efficient.
Space-constrained environments
— avoids 3× recursion overhead when working with very deep or large trees.
Ready to see it in action?
Step through the visualizer to watch the algorithm state update live.