Why do Preorder, Inorder, Postorder, and Level-Order traversals visit the exact same tree in four completely different orders—and how does Morris Traversal walk a tree in O(1) space without a stack or recursion?
In 30 Seconds
Tree Traversals visit every node in a binary tree systematically in O(N) time. DFS (Depth-First Search) plunges down subtrees using the Call Stack (Preorder: Root-Left-Right, Inorder: Left-Root-Right, Postorder: Left-Right-Root), whereas BFS (Breadth-First Search / Level-Order) sweeps across horizontal floors using a FIFO Queue.
The Real-World Analogy: Walking Around the Outside Perimeter of a Tree
Imagine drawing a continuous dashed line hugging the outside edge of a tree starting from the left of the root:
- Preorder: Record a node the first time your pen passes its left side (great for serializing/cloning a tree).
- Inorder: Record a node when your pen passes directly underneath it (prints a Binary Search Tree in sorted ascending order!).
- Postorder: Record a node when your pen passes its right side (used when deleting nodes or computing bottom-up subtree heights).
Under the Hood: Call Stack Frames, Queue Peak Width & Morris O(1) Threading
- Memory Profile of DFS vs. BFS: DFS stores at most one root-to-leaf path on the call stack: O(H) space ($O(\log N)$ on balanced trees, $O(N)$ on skewed chains). Conversely, BFS stores an entire horizontal level inside its queue: O(W) space—on a balanced tree, the bottom level holds $N/2$ nodes (O(N) peak memory), whereas on a skewed chain, queue width is just O(1)!
- Morris Inorder Traversal (Zero Stack, Zero Recursion — O(1) Space): By temporarily wiring a leaf's empty
rightpointer back up to its inorder successor (creating a temporary "thread") and restoring it toNoneon the second visit, Morris Traversal walks the entire tree in O(N) time and strictly O(1) memory!
Picture This
[ 1 ]
/ \
[ 2 ] [ 3 ]
/ \
[ 4 ] [ 5 ]
Preorder (Root -> Left -> Right): [1, 2, 4, 5, 3]
Inorder (Left -> Root -> Right): [4, 2, 5, 1, 3]
Postorder (Left -> Right -> Root): [4, 5, 2, 3, 1]
Level-Order (BFS Queue by Floor): [[1], [2, 3], [4, 5]]
Show Me The Code
# Day 21: DFS (Iterative & Recursive) + Level-Order BFS Tree Traversals in Python
from collections import deque
def inorder_iterative(root):
"""Iterative Inorder DFS using explicit Stack (avoids RecursionError on deep trees)."""
res, stack = [], []
curr = root
while curr or stack:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
res.append(curr.val)
curr = curr.right
return res
def level_order_bfs(root):
"""Level-Order BFS returning nodes grouped level by level in O(N) time."""
if not root:
return []
res = []
queue = deque([root])
while queue:
level_size = len(queue) # Snapshot exact width of current floor!
level = []
for _ in range(level_size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(level)
return res
Speed & Memory
| Traversal | Time | Balanced Tree Space | Skewed Tree Space | Primary Use Case |
|---|---|---|---|---|
| DFS (Pre / In / Post) | O(N) | O(log N) | O(N) | Subtree aggregation, BST sorting, tree serialization. |
| BFS (Level-Order) | O(N) | O(N) (width $N/2$) | O(1) | Minimum depth, right-side view, zigzag level traversal. |
Traps To Avoid
- Trap 1: Forgetting to snapshot
level_size = len(queue)before the innerforloop in BFS. Fix: Becausequeuegrows as you append children, looping overrange(len(queue))freezes the exact count of nodes on the current level! - Trap 2: Using recursive DFS on trees with depth $> 1,000$ in Python. Fix: Use the iterative explicit-stack template above so heap memory handles deep trees without hitting
RecursionError.
Practice
- Easy: Return the right-side view of a binary tree (the last node visible at each level from top to bottom).
- Medium: Return the zigzag level-order traversal of a binary tree (left-to-right on even levels, right-to-left on odd levels).
- Hard: Reconstruct a binary tree from its
preorderandinordertraversal arrays in O(N) time using a value-to-index Hash Map.
TL;DR
- DFS (Preorder, Inorder, Postorder) uses a Stack (O(H) space), while BFS (Level-Order) uses a Queue (O(W) space).
- Snapshot
level_size = len(queue)on each BFS iteration to group nodes cleanly by level.
References consulted: GeeksforGeeks Tree Traversals — referenced for verification — all content above is original.
Covered Log Update
Already covered: [Big-O notation, Arrays, Two Pointers, Strings, Sliding Window, Prefix Sums, Recursion basics, Singly Linked List, Doubly Linked List, Stack, Queue, Deque, Fast & Slow pointers, Binary Search, Bubble/Selection/Insertion Sort, Merge Sort, Quick Sort, Counting & Bucket Sort, Hashing & Hash Maps, Binary Tree, Tree Traversals (DFS/BFS)]