Skip to main content

6.3 Binary Tree Traversals: DFS (Recursive & Iterative) & BFS Level-Order

πŸ“šModule 06 β€’ Trees & HierarchiesTopic 6.3⏱️18 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ 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:

  1. Depth-First Search (DFS) Traversals (Preorder, Inorder, Postorder): Explores branches vertically using the call stack (or an explicit heap Stack), consuming O(h)\mathcal{O}(h) space proportional to height hh.
  2. Breadth-First Level-Order Traversal (BFS): Explores horizontally floor-by-floor using a FIFO Queue, consuming O(w)\mathcal{O}(w) space proportional to maximum tree width ww.

🧭 DFS vs. BFS Architectural Paradigm​

Depth-First Search (DFS) vs. Level-Order Breadth-First (BFS)

Call-stack depth unwinding versus FIFO queue horizontal sweeps

DFS Family

Preorder, Inorder & Postorder (Stack)

🌲
Dominant Architecture / DomainAST Evaluation β€’ BST Sorting β€’ Safe Freeing
  • β€’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!
"Visit vertically via LIFO unwinding: Pre (Parent 1st), In (Middle), Post (Parent Last)."
BFS Level Sweep

Level-Order Traversal (FIFO Queue)

🚢
Dominant Architecture / DomainShortest Depth β€’ Serialization β€’ CBT Checks
  • β€’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).
"Enqueues children horizontally in arrival order to process trees layer by layer."

πŸ”„ 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): Θ(n)\Theta(n) β€” every node is entered once and NULL pointers are checked n+1n + 1 times.
  • Space Complexity: Θ(h)\Theta(h) auxiliary stack frames (Θ(log⁑n)\Theta(\log n) balanced, Θ(n)\Theta(n) 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 (F Root): Enqueue F -> pop F, enqueue B, G -> pop B, enqueue A, D -> pop G, enqueue I -> pop A, D (C, E) -> pop I (H) -> pop C, E, H. Result: F B G A D I C E H.

πŸ“š Iterative DFS Traversals Using an Explicit Heap Stack​

On trees with depth h>100,000h > 100{,}000, deep C recursion risks Hardware Call-Stack Overflow. Replacing recursion with an explicit heap-allocated LIFO Stack eliminates crash limits while keeping Θ(n)\Theta(n) 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​

πŸ“Problem Statementtheorem

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): Root 10, Left subtree (20, right=40), Right subtree (30, 50, 60) β€…β€ŠβŸΉβ€…β€Š\implies 10, 20, 40, 30, 50, 60.
  • Inorder (L -> N -> R): Left (NULL, 20, 40), Root 10, Right (50, 30, 60) β€…β€ŠβŸΉβ€…β€Š\implies 20, 40, 10, 50, 30, 60.
  • Postorder (L -> R -> N): Left (40, 20), Right (50, 60, 30), Root 10 β€…β€ŠβŸΉβ€…β€Š\implies 40, 20, 50, 60, 30, 10.
  • Level-Order (Queue): Level 0 [10] -> Level 1 [20, 30] -> Level 2 [40, 50, 60] β€…β€ŠβŸΉβ€…β€Š\implies 10, 20, 30, 40, 50, 60.

Example 2: Tracing Explicit-Stack Iterative Inorder​

πŸ“Problem Statementtheorem

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:​

  1. Slide down left spine from B: push B, push A. Stack [B, A]. curr hits NULL.
  2. Pop A, print A. curr = A->right = NULL. Stack [B].
  3. curr is NULL -> pop B, print B. Step right: curr = D. Stack [].
  4. Slide left from D: push D, push C. Stack [D, C]. curr hits NULL.
  5. Pop C, print C. Pop D, print D.
  • Exact printed output: A, B, C, D.

Example 3: Tree Deallocation Bug (Preorder vs. Postorder)​

πŸ“Problem Statementtheorem

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​

Core Conceptual Questions
  • Why Inorder Sorts BSTs: Because left descendants are strictly smaller and right descendants are strictly larger, visiting Left -> Root -> Right prints 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 nn-node binary tree has n+1n + 1 NULL child pointers; recursive DFS checks base if (node == NULL) exactly n+1n + 1 times.
  • Iterative vs. Recursive Space Equivalence: Both explicit-stack iterative DFS and recursive DFS use Θ(h)\Theta(h) auxiliary memory, except an explicit heap stack avoids small fixed OS call-stack overflow limits (~1–8 MB).
Common Interview Traps: Architectural Trade-Offs
  • Pushing Left Before Right in Iterative Preorder: Pushing left then right pops right first (LIFO!), scrambling output into N -> R -> L. Always push right first so left stays on Top of Stack!
  • Freeing Nodes in Preorder: Calling free(node) before recursing into node->left causes immediate Use-After-Free memory corruption. Always free trees in Postorder.
  • Assuming Level-Order Uses O(h)\mathcal{O}(h) Space: A balanced binary tree of nn nodes has height h=log⁑2nh = \log_2 n, yet its bottom level holds β‰ˆn/2\approx n/2 nodesβ€”meaning Level-Order BFS Queue peaks at Θ(n)\Theta(n) RAM, not Θ(log⁑n)\Theta(\log n)!
  • Forgetting curr != NULL Condition in Iterative Inorder: Looping solely on while (!isEmpty(S)) terminates prematurely when root pops and stack briefly becomes empty right before descending the entire right subtree! Always write while (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.

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.