AlgoViz

Iterative DFS

medium 22 min

Iterative DFS replaces the hidden call stack with an explicit one.

Video lesson · Chapter 1 of 9

Archive closeout

0:00 / 7:11

Iterative DFS in 75 seconds

1:19Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Decide what a frame must remember. The node (or cell) plus enough state to know what to do when it comes back to the top: enter or exit, next neighbour, partial result

Understand it

Start here

Why make the stack explicit

Every recursive DFS already uses a stack: the call stack. Iterative DFS keeps the same last-in, first-out walk in an ordinary list that you own. Same visiting order, same O(n)O(n) or O(V+E)O(V + E) time. What changes is who holds the frames, and that brings three things recursion cannot give: no depth limit, the ability to pause, and full control over what each frame stores.

  • Recap: tree traversals

    Iterative preorder, inorder and postorder with a stack, and the reverse trick, are taught step by step in Tree DFS. This page starts where that one stops.

  • Recap: the stack

    Push and pop at the top in O(1)O(1); a Python list with append and pop. See Stack.

  • Recap: call frames

    How each call waits for the one above it is walked through in Recursion: factorial.

  • Recap: graphs and grids

    Adjacency lists, visited sets and 4-direction neighbours: Intro to graphs and Matrix DFS.

Under the hood

What a recursive call really stores

Each call pushes a stack frame: its arguments, its local variables and the return address (which line to resume at when the inner call returns). Frames live in a fixed-size region of memory, and the interpreter may also impose its own counter. For DFS the depth dd is the length of the current path, so the memory is:

Call-stack memory

Scall=d×fd≤h (tree),d≤V (graph),d≤R⋅C (grid)S_{\text{call}} = d \times f \qquad d \le h \text{ (tree)}, \quad d \le V \text{ (graph)}, \quad d \le R \cdot C \text{ (grid)}
ff is the size of one frame. A balanced tree has h=log⁡2nh = \log_2 n, but a skewed tree, a path graph or a snake-shaped region makes dd as large as the input.

Typical recursion ceilings (defaults, they vary by platform)

LanguageWhat limits depthRough depth before failureError
Python (CPython)sys.getrecursionlimit(), default 1000about 1,000 callsRecursionError
Javathread stack size (-Xss), often 512 KB to 1 MBabout 10,000 to 20,000 simple callsStackOverflowError
JavaScript (V8)engine stack sizeabout 10,000 callsRangeError
C / C++OS thread stack, often 8 MB on Linux, 1 MB on Windowsdepends on frame sizesegmentation fault
An explicit stack lives on the heap, so its only limit is memory. One frame in a list is a small tuple, far cheaper than an interpreter frame.

The decision

When to avoid recursion

Recursion or an explicit stack?

Depth is the usual reason. Skewed trees (inserting sorted keys into a plain BST), linked-list-shaped graphs and large grids all reach it.

Make it iterative when

  • Input depth is unbounded: skewed trees, chains of 10^5 nodes, 1000 × 1000 grids.
  • You need an iterator or generator that hands out one node at a time (a BST iterator).
  • You need to stop early and resume later, or run many walks side by side.
  • The platform has a small stack: embedded systems, worker threads, browsers.

Recursion is fine when

  • Depth is small and known: a balanced BST has about 20 levels for a million keys.
  • Readability matters most and the input is bounded (most interview trees).
  • Backtracking with clean undo where depth equals the number of choices, like N-Queens.
  • You will start recursive in the interview, then convert if asked.

Recursive vs iterative at a glance

AspectRecursiveIterative
Code lengthshorterlonger
Stack overflow riskyes, past the depth limitno, only memory
Control (pause, resume, custom frames)lessmore
Time and spaceO(n)O(n), O(h)O(h)O(n)O(n), O(h)O(h) (same)
In interviewsusually accepted firststrong follow-up answer

Already covered

Recap: the three stack traversals

Tree 1 / 2, 3 / 4, 5, 6, 7 with an explicit stack

OrderResultStack rule (PIP)
Preorder1, 2, 4, 5, 3, 6, 7pop and visit, then push right before left so left pops first
Inorder4, 2, 5, 1, 6, 3, 7go left till None pushing, pop and visit, then go right
Postorder4, 5, 2, 6, 7, 3, 1push left before right (gives root, right, left), then reverse
Full step-by-step walkthroughs of all three are in Tree DFS. The reverse trick needs O(n)O(n) extra for the output list; below is a postorder that does not.

Technique 1

Simulating the call stack with (node, state) frames

Any recursion can be converted mechanically. A real frame holds the arguments and a resume point. So store (node, state) in each stack entry, where state says which part of the function runs next. For DFS two states are enough: enter (first visit, schedule the children) and exit (children done, do the after-work). Return values go on a second stack or into a dictionary.

The enter / exit loop

The exit frame is pushed before the children, so it sits under them and comes back only after their whole subtrees are finished.
Python
class Node:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef evaluate(root):    stack, vals = [(root, False)], []    while stack:        node, seen = stack.pop()        if node.left is None:              # leaf: a number            vals.append(node.val)        elif not seen:                     # enter: schedule            stack.append((node, True))            stack.append((node.right, False))            stack.append((node.left, False))        else:                              # exit: combine            b, a = vals.pop(), vals.pop()            vals.append(a + b if node.val == "+" else a * b)    return vals[0]expr = Node("*", Node("+", Node(2), Node(3)), Node(4))print(evaluate(expr))   # 20
Evaluate the expression tree (2 + 3) * 4. The flag is the resume point; vals stands in for return values.
Edit and run it in your browser

Technique 2

Postorder with one stack and a prev pointer

Keep the current root-to-node path on the stack and remember prev, the last node you output. When the node on top has a right child, there are only two possibilities: you have not gone right yet, or you just came back from there. If top.right is prev, the right subtree is finished, so the node is ready to output.

One-stack postorder

Exactly the recursive order, emitted as you go: works for streaming and for bottom-up DP where a parent needs both children's answers.
Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef postorder(root):    out, stack = [], []    curr, prev = root, None    while curr or stack:        while curr:            stack.append(curr)            curr = curr.left        top = stack[-1]        if top.right and top.right is not prev:            curr = top.right        else:            out.append(top.val)            prev = stack.pop()    return outt = TreeNode(8, TreeNode(3, TreeNode(1), TreeNode(6)), TreeNode(10, None, TreeNode(14)))print(postorder(t))   # [1, 6, 3, 14, 10, 8]
Postorder on the BST 8 / 3, 10 / 1, 6, 14 without reversing anything.
Edit and run it in your browser

Technique 3

Morris inorder: O(1) extra space

The stack in inorder exists only to climb back to an ancestor. Morris finds a spare pointer for that job: the inorder predecessor of curr (rightmost node of its left subtree) always has right = None. Point it at curr (a thread), go left, and when the walk later follows the thread back, remove it and visit curr.

One Morris step

First arrival at a node builds its thread, second arrival removes it. When the loop ends every pointer is restored.

Why it is still linear

∑nodes with a left child2 ∣right spine of left subtree∣  ≤  2(n−1)  ⇒  T(n)=O(n),S(n)=O(1)\sum_{\text{nodes with a left child}} 2\,\lvert \text{right spine of left subtree} \rvert \;\le\; 2(n-1) \;\Rightarrow\; T(n) = O(n), \quad S(n) = O(1)
Each node with a left child searches for its predecessor twice (once to build, once to remove). Those searches walk right spines of different subtrees, which never share an edge, so the total is at most twice the edge count.
Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef morris_inorder(root):    out, curr = [], root    while curr:        if curr.left is None:            out.append(curr.val)            curr = curr.right        else:            pred = curr.left            while pred.right and pred.right is not curr:                pred = pred.right            if pred.right is None:                pred.right = curr        # thread                curr = curr.left            else:                pred.right = None        # unthread                out.append(curr.val)                curr = curr.right    return outt = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(5))print(morris_inorder(t))   # [1, 2, 3, 4, 5]print(morris_inorder(t))   # same again: the threads were removed
Morris inorder on 4 / 2, 5 / 1, 3. The tree is unchanged afterwards.
Edit and run it in your browser

Technique 4

Iterative DFS on graphs: mark on pop or on push

Graphs have cycles, so a node can be reached along many edges and you need a seen set. When you add to it changes the result. On the graph A-B, A-C, B-C, B-E, C-D (neighbours in alphabetical order), recursion visits A, B, C, D, E.

Mark on popMark on push
When a node joins seenwhen it is popped and processedwhen it is first pushed
Duplicates on the stackyes, skip them with continuenever
Order on the exampleA, B, C, D, E (same as recursion)A, B, E, C, D (different)
Peak stack sizeO(E)O(E)O(V)O(V)
Use fortrue DFS order, DFS tree, discovery and finish timesreachability, components, flood fill
Push neighbours in reverse so the first neighbour ends on top; otherwise even mark on pop explores them in the opposite order to recursion.

Choosing where to mark

Bridges, articulation points and finish-time orderings need real DFS order. Counting islands does not.
Python
adj = {"A": ["B", "C"], "B": ["A", "C", "E"], "C": ["A", "B", "D"],       "D": ["C"], "E": ["B"]}def dfs_on_pop(start):    seen, order, stack = set(), [], [start]    while stack:        u = stack.pop()        if u in seen:            continue        seen.add(u)        order.append(u)        for v in reversed(adj[u]):            if v not in seen:                stack.append(v)    return orderdef dfs_on_push(start):    seen, order, stack = {start}, [], [start]    while stack:        u = stack.pop()        order.append(u)        for v in reversed(adj[u]):            if v not in seen:                seen.add(v)                stack.append(v)    return orderprint(dfs_on_pop("A"))    # ['A', 'B', 'C', 'D', 'E']print(dfs_on_push("A"))   # ['A', 'B', 'E', 'C', 'D']
Both versions on the example graph.
Edit and run it in your browser

Technique 5

Flood fill and backtracking on a grid

A grid is a graph whose neighbours are the four adjacent cells (Matrix DFS covers the recursive version). A region can be as large as the whole grid, so on a 1000 × 1000 image a recursive fill may need a million nested calls. With an explicit stack and mark on push, each cell enters the stack at most once.

Python
def flood_fill(grid, sr, sc, new):    old = grid[sr][sc]    if old == new:        return grid                    # nothing to do, and avoids looping    R, C = len(grid), len(grid[0])    grid[sr][sc] = new    stack = [(sr, sc)]    while stack:        r, c = stack.pop()        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):            nr, nc = r + dr, c + dc            if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == old:                grid[nr][nc] = new                stack.append((nr, nc))    return gridg = [[1, 1, 0], [0, 1, 0], [1, 0, 1]]print(flood_fill(g, 0, 0, 2))          # [[2, 2, 0], [0, 2, 0], [1, 0, 1]]big = [[1] * 5000]                     # one long row: recursion would failprint(flood_fill(big, 0, 0, 7)[0][-1]) # 7
Iterative flood fill. Painting a cell is its visited mark, so no separate set is needed.
Edit and run it in your browser

Backtracking needs one more idea: when a path is abandoned, its choices must be undone. That is the exit frame again. Push (cell, False) to enter (mark it on the path), push (cell, True) under the neighbours, and when the exit frame pops, unmark the cell. This finds whether a word exists in a letter grid, or all paths through a maze, without recursion.

Python
def exists(board, word):    R, C = len(board), len(board[0])    for sr in range(R):        for sc in range(C):            if board[sr][sc] != word[0]:                continue            on_path = set()            stack = [(sr, sc, 0, False)]            while stack:                r, c, i, leaving = stack.pop()                if leaving:                    on_path.discard((r, c))    # undo the choice                    continue                if i == len(word) - 1:                    return True                on_path.add((r, c))                stack.append((r, c, i, True))  # undo after the subtree                for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):                    nr, nc = r + dr, c + dc                    if (0 <= nr < R and 0 <= nc < C and (nr, nc) not in on_path                            and board[nr][nc] == word[i + 1]):                        stack.append((nr, nc, i + 1, False))    return Falseboard = ["ABCE", "SFCS", "ADEE"]print(exists(board, "ABCCED"), exists(board, "SEE"), exists(board, "ABCB"))  # True True False
Iterative word search: the exit frame plays the role of the code after the recursive call (undo).
Edit and run it in your browser

Technique 6

Cycle detection with three colours

In a directed graph, reaching an already-seen node is not enough to prove a cycle: it may be a node finished on another branch. You need to know whether it is still on the current path. Three colours say exactly that, and the iterative version gets the timing right with the same exit frame as technique 1.

A node's colour over time

GRAY nodes are exactly the nodes whose exit frames are still on the stack: the current path. An edge to BLACK is a cross or forward edge and is safe.
Python
def has_cycle(adj):    WHITE, GRAY, BLACK = 0, 1, 2    color = {u: WHITE for u in adj}    for s in adj:        if color[s] != WHITE:            continue        stack = [(s, False)]        while stack:            u, leaving = stack.pop()            if leaving:                color[u] = BLACK                continue            if color[u] != WHITE:                continue            color[u] = GRAY            stack.append((u, True))            for v in reversed(adj[u]):                if color[v] == GRAY:                    return True                if color[v] == WHITE:                    stack.append((v, False))    return Falseg = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": [], "E": ["A"]}print(has_cycle(g))                    # Trueg["E"] = []print(has_cycle(g))                    # False: C -> D alone is not a cycle
On A→B, A→C, B→D, C→D, C→E, E→A the edge C→D reaches a BLACK node (fine) and E→A reaches a GRAY one (cycle).
Edit and run it in your browser

Complexity

Same Big O, different limits

TechniqueTimeExtra spaceNotes
(node, state) framesO(n)O(n)O(h)O(h)two frames per internal node
One-stack postorderO(n)O(n)O(h)O(h)no O(n)O(n) reversal list
Morris inorderO(n)O(n)O(1)O(1)modifies pointers temporarily
Graph DFS, mark on popO(V+E)O(V + E)O(V+E)O(V + E)stack may hold duplicates
Graph DFS, mark on pushO(V+E)O(V + E)O(V)O(V)order can differ from recursion
Grid flood fillO(R⋅C)O(R \cdot C)O(R⋅C)O(R \cdot C)each cell pushed at most once
Three-colour cycle checkO(V+E)O(V + E)O(V+E)O(V + E)exit frame turns GRAY to BLACK

Why mark on pop can hold O(E) entries

pushes≤∑udeg⁡(u)=2E  (undirected)⇒stack=O(E)\text{pushes} \le \sum_{u} \deg(u) = 2E \;(\text{undirected}) \quad\Rightarrow\quad \text{stack} = O(E)
Every edge can push its endpoint once before that endpoint is marked. Mark on push caps pushes at one per node, VV in total.

Recap

Key takeaways

Key points

  • Iterative DFS is recursion with the call stack moved into a list: same order, same Big O, no depth limit.
  • Python's default limit is about 1,000 frames; raising it does not grow the C stack, so convert deep recursion to a loop.
  • Any recursion converts with (node, state) frames: push an exit frame under the children to run code after them.
  • One-stack postorder: if top.right is prev you are returning from the right, so output and pop.
  • Morris inorder threads predecessors back to ancestors for O(1) extra space, then removes every thread.
  • Graphs: mark on pop for the exact recursive order (skip stale duplicates), mark on push for no duplicates and an O(V) stack.
  • Grids: mark on push, four directions, bounds first. Backtracking undoes choices in the exit frame.
  • Directed cycles need three colours: an edge to GRAY is a back edge; an edge to BLACK is safe.

Sources