A traversal visits every node of a tree exactly once in a systematic order. Depth-first traversals (pre-order, in-order, post-order) dive down one branch before backing up, while breadth-first (level-order) sweeps the tree one level at a time. Picking the right order is half of most tree problems: it decides whether you see a node before its children, between them, or after them.
Think of it like
Folders on your computer
Printing a folder listing shows each folder's name before its contents: that is pre-order. Computing disk usage needs every subfolder's total before the parent's total: that is post-order. A building inspector who checks every room on floor 1 before taking the stairs to floor 2 is doing level-order. Same folders, same rooms; the only difference is when you do the work.
Depth-first vs breadth-first
Depth-first search (DFS) follows one path all the way to a leaf, then backtracks. It needs a stack: either the call stack (recursion) or an explicit one. Breadth-first search (BFS) visits all nodes at depth 0, then depth 1, and so on, which needs a queue. These are the same two strategies as Depth-First Search and Breadth-First Search on graphs, simplified because a tree has no cycles and needs no visited set.
F
/ \
B G
/ \ \
A D I
/ \ /
C E H| Order | Rule | Output on the example |
|---|---|---|
| Pre-order | node, left, right | F B A D C E G I H |
| In-order | left, node, right | A B C D E F G H I |
| Post-order | left, right, node | A C E D B H I G F |
| Level-order | depth 0, depth 1, …; left to right | F B G A D I C E H |
Recursive traversals
Recursion mirrors the definition of a binary tree, so all three DFS orders are the same function with the visit placed on a different line. Each runs in O(n) time and uses O(h) stack space, where h is the height.
def dfs(node):
if node is None:
return
# PRE-order: visit(node) here
dfs(node.left)
# IN-order: visit(node) here
dfs(node.right)
# POST-order: visit(node) hereIterative traversals with an explicit stack
Interviewers often ask for the iterative versions, and production code needs them when trees can be deep enough to overflow the call stack. They are also how you build a lazy iterator that yields one node at a time.
Pre-order
- 1
Seed the stack
Push the root.
- 2
Pop and visit
Pop the top node and record it.
- 3
Push right, then left
The stack is LIFO, so pushing the right child first means the left child is popped and processed first.
- 4
Repeat
Continue until the stack is empty.
In-order
- 1
Slide left
From the current node, push every node on the way down the left spine.
- 2
Pop and visit
The top of the stack is the leftmost unvisited node: record it.
- 3
Turn right
Move to the popped node's right child and slide left again from there.
- 4
Repeat
Stop when the current node is null and the stack is empty.
Post-order
Post-order is the trickiest because a node must wait until both subtrees are finished. Two common solutions:
Reverse a modified pre-order
- Run pre-order but push left before right, giving node, right, left
- Reverse the output to get left, right, node
- Short and easy, but O(n) extra memory and not lazy
One stack plus a last-visited pointer
- Slide left like in-order, then peek at the top
- If it has an unfinished right child, go right; otherwise emit it
- True post-order: works for evaluation and streaming
Morris traversal: O(1) extra space
A binary tree with n nodes has n + 1 null child pointers. Morris traversal borrows them as temporary threads: before descending into a left subtree, it points the subtree's rightmost node (the in-order predecessor) back at the current node. When the walk later follows that thread, it knows the left side is finished, removes the thread and moves right. No stack, no recursion.
def morris_inorder(root):
out, cur = [], root
while cur:
if cur.left is None:
out.append(cur.val) # no left subtree: visit, go right
cur = cur.right
else:
pred = cur.left # find the in-order predecessor:
while pred.right and pred.right is not cur:
pred = pred.right # rightmost node of the left subtree
if pred.right is None:
pred.right = cur # first arrival: create the thread
cur = cur.left
else:
pred.right = None # second arrival: remove the thread
out.append(cur.val)
cur = cur.right
return outLevel-order traversal (BFS)
Put the root in a queue. Repeatedly dequeue a node, visit it, and enqueue its children. Because a queue is first-in, first-out, every node at depth d comes out before any node at depth d + 1.
Many problems need the levels kept separate (averages per level, right-side view, zigzag). The trick: at the start of each round, record the queue's current length k. Exactly those k nodes make up the current level; anything enqueued while processing them belongs to the next one.
- Zigzag order: alternate left-to-right and right-to-left by reversing every other level (or by appending to the front of a deque on odd levels).
- Right-side view: keep only the last node of each level.
- Minimum depth: the first leaf BFS dequeues is the shallowest, so you can stop early, which DFS cannot.
- Memory: the queue holds up to one full level. A perfect tree's last level has about n / 2 nodes, so BFS uses O(w) space where w is the maximum width.
Which traversal when?
| Task | Traversal | Why |
|---|---|---|
| Copy, clone or serialize a tree | Pre-order | A parent is created before its children. With null markers, pre-order alone can be decoded back into the tree. |
| List BST keys in sorted order, validate a BST, k-th smallest | In-order | In-order on a BST yields keys in ascending order. |
| Delete or free a tree, compute sizes or heights | Post-order | Children must be finished before the parent is processed. |
| Evaluate an expression tree | Post-order | Operands are computed before the operator applies; post-order is Reverse Polish Notation. |
| Shallowest leaf, per-level statistics, right-side view | Level-order | Nodes come out in increasing depth. |
def serialize(node, out):
if node is None:
out.append("#") # marks the missing child
return
out.append(str(node.val))
serialize(node.left, out)
serialize(node.right, out)
# The example tree serializes to:
# F B A # # D C # # E # # G # I H # # #Rebuilding a tree from two traversals
Without null markers, a single traversal is ambiguous: many trees share the same pre-order. But pre-order plus in-order uniquely determines a binary tree with distinct values. The first pre-order value is the root; finding it in the in-order sequence splits everything else into the left subtree (to its left) and the right subtree (to its right).
- 1
Root
preorder
[3, 9, 20, 15, 7], inorder[9, 3, 15, 20, 7]. The root is3, found at inorder index 1. - 2
Split
Inorder left of 3 is
[9](1 node), right is[15, 20, 7]. So the next 1 pre-order value belongs to the left subtree, the rest to the right. - 3
Left subtree
Pre-order
[9], in-order[9]: a single leaf. - 4
Right subtree
Pre-order
[20, 15, 7]: root20, which splits in-order[15, 20, 7]into[15]and[7]. - 5
Result
3with left child9and right child20, which has children15and7.
def build_tree(preorder, inorder):
index = {v: i for i, v in enumerate(inorder)} # value -> inorder position
pre = iter(preorder)
def build(lo, hi): # subtree whose values are inorder[lo..hi]
if lo > hi:
return None
root = TreeNode(next(pre))
mid = index[root.val]
root.left = build(lo, mid - 1) # left first: pre-order lists it first
root.right = build(mid + 1, hi)
return root
return build(0, len(inorder) - 1)Complexity
| Traversal | Time | Extra space | Notes |
|---|---|---|---|
| Recursive pre / in / post-order | O(n) | O(h) | Call stack; h = n on a skewed tree |
| Iterative with explicit stack | O(n) | O(h) | Same bound, but no recursion limit |
| Morris in-order / pre-order | O(n) | O(1) | Temporarily rewires null pointers |
| Level-order (BFS) | O(n) | O(w) | w = max width, up to about n / 2 |
BST iterator next() | O(1) | O(h) | Amortized; each node pushed and popped once |
| Rebuild from pre-order + in-order | O(n) | O(n) | Hash map for in-order positions |
Every traversal must touch each node, so O(n) time is optimal. The differences are in memory and in the order nodes are produced.
Implementation
The same recursion with the visit placed before, between or after the two child calls. Results are appended to a shared list.
from typing import Optional
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def preorder(node: Optional[TreeNode], out: list) -> list:
if node:
out.append(node.val) # visit before the children
preorder(node.left, out)
preorder(node.right, out)
return out
def inorder(node: Optional[TreeNode], out: list) -> list:
if node:
inorder(node.left, out)
out.append(node.val) # visit between the children
inorder(node.right, out)
return out
def postorder(node: Optional[TreeNode], out: list) -> list:
if node:
postorder(node.left, out)
postorder(node.right, out)
out.append(node.val) # visit after the children
return outKey takeaways
- Pre-, in- and post-order are the same DFS with the visit placed before, between or after the child calls; level-order is BFS with a queue.
- Choose by dependency: pre-order when parents come first (copy, serialize), in-order for sorted BST output, post-order when children come first (delete, evaluate, heights).
- Iterative DFS replaces the call stack with an explicit one: pre-order pushes right before left, in-order slides left, post-order tracks the last emitted node.
- Morris traversal reaches O(1) extra space by temporarily threading null right pointers back to in-order successors.
- Snapshot the queue size at the start of each BFS round to process one level at a time.
- Pre-order (or post-order) plus in-order uniquely rebuilds a tree with distinct values; a hash map keeps it O(n).
Common pitfalls
- Pushing the left child before the right in iterative pre-order, which produces node, right, left instead.
- Using
Array.prototype.shift()as a queue in JavaScript, which is O(n) per call and makes BFS quadratic on large trees. - Forgetting the null base case, or guarding only one child before recursing, which crashes with a null-pointer error in Java and C++.
- Stopping a Morris traversal early (for example after finding the k-th element), which leaves threads in the tree and corrupts it.
- Searching the in-order array linearly during reconstruction, which turns an O(n) algorithm into O(n²).
Interview tips
- Before coding, say which order you need and why ("I need children's results first, so post-order"). It shows you understand the problem's dependencies.
- Be ready to convert any recursive traversal to an iterative one; iterative in-order and post-order are classic follow-ups.
- If asked for O(1) space, mention Morris traversal and its trade-off: it temporarily mutates the tree.
- For level-based questions, write the queue-size snapshot loop from memory; it is the template for a dozen problems.
Real-world applications
- Serializing trees to disk or the network (pre-order with null markers).
- Compilers evaluate and generate code from abstract syntax trees in post-order.
- Database and file-system range scans walk ordered trees in in-order.
- Garbage collectors and destructors free child objects before parents (post-order).
- UI frameworks and game engines render scene graphs level by level or in pre-order.
Practice problems
Test yourself
Which traversal of a binary search tree outputs its keys in ascending order?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.