Iteration & Traversal

RoadmapsDSA

Overview

Iteration is the control-flow mechanism of repeating a code block until a condition is met, agnostic to any data structure. Traversal is the strategic application of iteration (or recursion) to visit every node or element in a specific data structure exactly once, guided by that structure's topology. Every traversal uses iteration as its engine, but not every iteration is a traversal.

Modern applications must process vast datasets stored in non-contiguous, dynamically allocated memory structures — linked lists, trees, graphs — where hardcoded indices fail at runtime. Traversal algorithms provide a principled, structure-aware navigation strategy that ensures complete, non-redundant coverage.

Where used: Linear traversal: reversing a linked list by maintaining prev/curr/next pointers in O(n) time and O(1) space, BFS traversal: finding the shortest path in an unweighted graph using a Queue for level-order discovery, DFS traversal: syntax tree evaluation in compilers and maze-solving via recursive stack-based backtracking

Why learn this

Aha moment

# Reverse a linked list: pure iteration or traversal?
class Node:
    def __init__(self, val): self.val, self.next = val, None

def reverse(head):
    prev, curr = None, head
    while curr:             # iteration engine
        nxt = curr.next     # traversal: following structural links
        curr.next = prev
        prev = curr
        curr = nxt
    return prev

Prediction: The while loop is just iteration — it could be replaced with a counter.

Common guess: This is just iteration because it uses a while loop.

The while loop IS the iteration engine, but what makes this a traversal is the explicit navigation of non-contiguous memory via structural links (curr.next). You cannot replace 'curr = nxt' with a counter — the next node's address is unknown until you follow the pointer. The topology of the linked list, not a numeric condition, governs the traversal.

Common mistakes

Glossary

dynamically allocated memory
Memory space that is requested and assigned while the program is running, not fixed beforehand.
topological constraints
The specific physical or logical structure that dictates how data is connected (like a line vs a tree).
iterator invalidation exceptions
An error that occurs when you try to change a collection while you are in the middle of looping through it.

Recall questions

Understanding checks

If you replace the Queue in a BFS implementation with a Stack, what traversal pattern does the algorithm produce, and why does this break shortest-path guarantees?

Replacing the Queue with a Stack produces DFS — the algorithm dives as deep as possible along one branch before backtracking. This breaks shortest-path guarantees because nodes are no longer discovered in level order; a deeper node on a longer path may be reached before a shallower node on a shorter path.

The Queue's FIFO property is the structural mechanism that enforces level-order discovery. The data structure choice is not cosmetic — it defines the fundamental traversal topology.

A developer writes: 'I used a for-loop to sum integers from 1 to n by iterating through a list. I traversed the list to get the answer.' Identify the two errors in this statement.

Error 1: It is iteration, not traversal — the loop processes numbers computationally, not nodes in a structural topology. Error 2: Even framing it as iteration reveals a missed optimization — Gauss's summation formula gives the answer in O(1) without any loop at all.

Traversal requires structural intent and a data structure to navigate. Recognizing when a mathematical shortcut eliminates the need for iteration entirely is a key signal of algorithmic maturity.

Practice tasks

Convert iterative BFS to DFS by changing one data structure

The starter code performs BFS level-order traversal on a binary tree (LeetCode 102). Modify it to perform DFS pre-order traversal by replacing exactly one data structure and adjusting the child insertion order. Add a comment explaining the invariant that each data structure maintains.

Continue learning

Previous: What is an Algorithm?

Previous: Tracing State & Loop Invariants

Return to DSA Roadmap