6.3 Binary Tree Traversals: DFS (Recursive & Iterative) & BFS Level-Order
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy: Attendance Order on a Tour Around a Museum Wingβ
To linearize a branching 2D tree into a 1D list visiting every node exactly once, walk clockwise around the outside boundary of the tree starting above the Rootβtouching each node three times (on its Left, Bottom, and Right):
- Preorder (
N -> L -> R, Left-Side Touch): Record each room the very moment you enter it for the first time before visiting its left/right wings! - Inorder (
L -> N -> R, Bottom-Side Touch): Record each room between finishing its left wing and entering its right wing. - Postorder (
L -> R -> N, Right-Side Touch): Record each room last, strictly after finishing both left and right wings! - Level-Order (Sweep Floor by Floor): Check every room on Floor 0, then all rooms on Floor 1 left-to-right, then Floor 2!
π» Bridging to Computer Science: Stack Recursion vs. FIFO Queue Sweepsβ
Every tree traversal falls into one of two execution engines:
- Depth-First Search (DFS) Traversals (
Preorder,Inorder,Postorder): Explores branches vertically using the call stack (or an explicit heap Stack), consuming space proportional to height . - Breadth-First Level-Order Traversal (BFS): Explores horizontally floor-by-floor using a FIFO Queue, consuming space proportional to maximum tree width .
πTable of Contents
- π§ DFS vs. BFS Architectural Paradigm
- π The Four Canonical Traversals & C Implementations
- π Iterative DFS Traversals Using an Explicit Heap Stack
- π Real-World Production Context: Compilers, Garbage Cleanup & Serialization
- π Numerical Applications & Worked Examples
- π― Exam & Interview Pitfall Check
- π Navigation & Next Steps
π§ DFS vs. BFS Architectural Paradigmβ
Depth-First Search (DFS) vs. Level-Order Breadth-First (BFS)
Call-stack depth unwinding versus FIFO queue horizontal sweeps
Preorder, Inorder & Postorder (Stack)
- β’Dives all the way down the leftmost path before backtracking.
- β’Natural recursion uses O(h) stack space (worst-case O(n) on skewed trees).
- β’Activation Tree Link: procedure CALL order matches Preorder; RETURN order matches Postorder!
Level-Order Traversal (FIFO Queue)
- β’Visits every node at depth k completely before touching depth k + 1.
- β’Cannot use naive single-branch recursionβstrictly requires an explicit FIFO Queue.
- β’Memory footprint scales with widest level O(w) (up to n/2 leaves at base).
π The Four Canonical Traversals & C Implementationsβ
1. Preorder (Node -> Left -> Right), Inorder (Left -> Node -> Right) & Postorder (Left -> Right -> Node)β
Notice the recursive implementations differ solely in where printf sits relative to the two recursive calls:
// 1. Preorder (N -> L -> R): Prints upon entering activation frame (Prefix & tree cloning)
void preorder(const struct TreeNode *node) {
if (node == NULL) return;
printf("%c ", node->data);
preorder(node->left);
preorder(node->right);
}
// 2. Inorder (L -> N -> R): Visits BST keys in strictly sorted ascending order!
void inorder(const struct TreeNode *node) {
if (node == NULL) return;
inorder(node->left);
printf("%c ", node->data);
inorder(node->right);
}
// 3. Postorder (L -> R -> N): Children finish before parent (Tree deletion / folder size)
void postorder(const struct TreeNode *node) {
if (node == NULL) return;
postorder(node->left);
postorder(node->right);
printf("%c ", node->data);
}
- Time Complexity (All Three): β every node is entered once and
NULLpointers are checked times. - Space Complexity: auxiliary stack frames ( balanced, worst-case skewed).
2. Level-Order Traversal (BFS via FIFO Queue)β
void levelOrder(struct TreeNode *root) {
if (root == NULL) return;
Queue *q = createQueue();
enqueue(q, root);
while (!isEmpty(q)) {
struct TreeNode *curr = dequeue(q);
printf("%c ", curr->data);
if (curr->left != NULL) enqueue(q, curr->left);
if (curr->right != NULL) enqueue(q, curr->right);
}
}
- Trace on Reference Tree (
FRoot): EnqueueF-> popF, enqueueB, G-> popB, enqueueA, D-> popG, enqueueI-> popA, D(C, E) -> popI(H) -> popC, E, H. Result:F B G A D I C E H.
π Iterative DFS Traversals Using an Explicit Heap Stackβ
On trees with depth , deep C recursion risks Hardware Call-Stack Overflow. Replacing recursion with an explicit heap-allocated LIFO Stack eliminates crash limits while keeping speed:
// Iterative Preorder: Push RIGHT child before LEFT child so LEFT pops first (LIFO)!
void iterativePreorder(struct TreeNode *root) {
if (root == NULL) return;
Stack *S = createStack();
push(S, root);
while (!isEmpty(S)) {
struct TreeNode *curr = pop(S);
printf("%c ", curr->data);
if (curr->right != NULL) push(S, curr->right); // Pushed 1st -> popped 2nd
if (curr->left != NULL) push(S, curr->left); // Pushed 2nd -> popped 1st!
}
}
// Iterative Inorder: Slide all the way left, pop & print, then step right
void iterativeInorder(struct TreeNode *root) {
Stack *S = createStack();
struct TreeNode *curr = root;
while (curr != NULL || !isEmpty(S)) {
while (curr != NULL) {
push(S, curr);
curr = curr->left;
}
curr = pop(S);
printf("%c ", curr->data);
curr = curr->right;
}
}
π Real-World Production Context: Compilers, Garbage Cleanup & Serializationβ
Traversal Algorithms in Production Systems
Mapping Preorder, Inorder, Postorder, and Level-Order to engineering tasks
AST Cloning & Prefix Emit
Preorder (N-L-R)- Allocates each parent node before linking recursive left/right subtrees during syntax tree duplication.
- Directly emits Polish Prefix operators ahead of operands.
Ordered Index Range Scans
Inorder (L-N-R)- Streams sorted database keys directly from balanced BSTs without running an O(n log n) sort.
- Evaluating AST expressions yields natural human infix syntax.
Safe Tree Deallocation & du
Postorder (L-R-N)- Must free Left and Right children BEFORE calling free(node) so child pointers are never dangling!
- Computes directory disk usage (du) bottom-up by summing child folder sizes.
Codec Tree Serialization
Level-Order (BFS)- Serializes binary trees cleanly row-by-row for compact network transmission.
- Checks whether a binary tree satisfies Complete Binary Tree array invariants.
π Numerical Applications & Worked Examplesβ
Example 1: Complete 4-Traversal Trace on an Asymmetric Treeβ
Given the 6-node binary tree: Root = 10, 10->left = 20, 10->right = 30, 20->right = 40, 30->left = 50, 30->right = 60.
Compute its exact Preorder, Inorder, Postorder, and Level-Order traversal sequences.
Step-by-Step Solution:β
- Preorder (
N -> L -> R): Root10, Left subtree(20, right=40), Right subtree(30, 50, 60)10, 20, 40, 30, 50, 60. - Inorder (
L -> N -> R): Left(NULL, 20, 40), Root10, Right(50, 30, 60)20, 40, 10, 50, 30, 60. - Postorder (
L -> R -> N): Left(40, 20), Right(50, 60, 30), Root1040, 20, 50, 60, 30, 10. - Level-Order (
Queue): Level 0[10]-> Level 1[20, 30]-> Level 2[40, 50, 60]10, 20, 30, 40, 50, 60.
Example 2: Tracing Explicit-Stack Iterative Inorderβ
Trace the contents of explicit stack S and output buffer when running iterativeInorder() on the reference subtree B (left: A, right: D -> (left: C)).
Step-by-Step Solution:β
- Slide down left spine from
B: pushB, pushA. Stack[B, A].currhitsNULL. - Pop
A, printA.curr = A->right = NULL. Stack[B]. currisNULL-> popB, printB. Step right:curr = D. Stack[].- Slide left from
D: pushD, pushC. Stack[D, C].currhitsNULL. - Pop
C, printC. PopD, printD.
- Exact printed output:
A, B, C, D.
Example 3: Tree Deallocation Bug (Preorder vs. Postorder)β
A developer tries freeing a heap-allocated tree using:
void destroy(struct TreeNode *root) {
if (!root) return;
free(root);
destroy(root->left);
destroy(root->right);
}
Identify the bug and rewrite using the mandatory traversal order.
Step-by-Step Solution:β
Calling free(root) before visiting root->left and root->right triggers Use-After-Free undefined behavior: root's memory is already returned to the heap before dereferencing root->left! Safe destruction MUST use Postorder:
void destroySafe(struct TreeNode *root) {
if (!root) return;
destroySafe(root->left);
destroySafe(root->right);
free(root); // Safe: both subtrees already freed!
}
π― Exam & Interview Pitfall Checkβ
- Why Inorder Sorts BSTs: Because left descendants are strictly smaller and right descendants are strictly larger, visiting
Left -> Root -> Rightprints keys in ascending sorted sequence. - Activation Tree Equivalence: In recursive execution, the chronological sequence of function calls matches Preorder, while the chronological sequence of function returns matches Postorder.
- Null-Check Leaf Cost: Every -node binary tree has
NULLchild pointers; recursive DFS checks baseif (node == NULL)exactly times. - Iterative vs. Recursive Space Equivalence: Both explicit-stack iterative DFS and recursive DFS use auxiliary memory, except an explicit heap stack avoids small fixed OS call-stack overflow limits (~1β8 MB).
- Pushing Left Before Right in Iterative Preorder: Pushing
leftthenrightpopsrightfirst (LIFO!), scrambling output intoN -> R -> L. Always pushrightfirst soleftstays on Top of Stack! - Freeing Nodes in Preorder: Calling
free(node)before recursing intonode->leftcauses immediate Use-After-Free memory corruption. Always free trees in Postorder. - Assuming Level-Order Uses Space: A balanced binary tree of nodes has height , yet its bottom level holds nodesβmeaning Level-Order BFS Queue peaks at RAM, not !
- Forgetting
curr != NULLCondition in Iterative Inorder: Looping solely onwhile (!isEmpty(S))terminates prematurely when root pops and stack briefly becomes empty right before descending the entire right subtree! Always writewhile (curr != NULL || !isEmpty(S)).
π Navigation & Next Stepsβ
Having learned how to generate 1D traversal streams from 2D trees, we now solve the inverse problem: which traversal pairs can uniquely reconstruct the exact original 2D binary tree in Topic 6.4.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.