What is the difference between DFS recursive and iterative implementations and their implications?

Why Interviewers Ask This

Senior Data Structures & Algorithms engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.

Answer

DFS can be implemented recursively or iteratively, with important differences: Recursive DFS: uses the implicit call stack; code is clean and natural; each recursive call stores local state (current node, iterator position); handles backtracking implicitly. Limitations: (1) Stack overflow for deep graphs (Python default recursion limit ~1000, can be hit for large trees); (2) Hard to pause/resume (generators help). Code: def dfs(node): visited.add(node); for neighbor in graph[node]: if neighbor not in visited: dfs(neighbor). Iterative DFS (explicit stack): push source; while stack: pop, process, push neighbors. Note: this visits in different order than recursive DFS — recursive processes neighbors left-to-right, pushing each then backtracking; iterative pushes all neighbors then pops (LIFO), so rightmost neighbor is visited first. For exact recursive order iteratively: push neighbors in reverse order. Pre-order is naturally iterative; post-order requires marking nodes or using two stacks; in-order is trickier iteratively. Implications: iterative DFS: (1) No stack overflow; (2) Better for very deep graphs; (3) Easier to pause (generators); (4) More explicit control. Recursive DFS: (1) Elegant, concise; (2) Natural for backtracking; (3) The actual call stack IS the DFS stack. For tree problems (depth ≤ few thousand), recursive is fine and cleaner. For graphs that could be deep, iterative or use sys.setrecursionlimit in Python.

Pro Tip

This topic has Data Structures & Algorithms-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.