Understanding BFS vs DFS — Implementation Guide
Dive into the technical implementation of BFS and DFS. Learn about queue vs stack data structures, iterative vs recursive approaches, and see production-ready code in multiple languages.
Dive into the technical implementation of BFS and DFS. Learn about queue vs stack data structures, iterative vs recursive approaches, and see production-ready code in multiple languages.
Author
Mr. Oz
Date
Read
8 mins
Level 2
Now that you understand the conceptual difference between BFS and DFS from Level 1, let's dive into how to implement them in code. The key insight is understanding which data structure each uses.
The fundamental difference between BFS and DFS comes down to one choice: how do we store nodes to visit next?
First-In-First-Out (FIFO)
Process nodes in the order they were discovered → level by level
Last-In-First-Out (LIFO)
Process most recently discovered nodes first → go deep
from collections import deque
def bfs(root):
if not root:
return []
result = []
queue = deque([root]) # Queue for BFS
while queue:
node = queue.popleft() # FIFO: remove from front
result.append(node.val)
# Add children to back of queue
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
Key: popleft() removes from front (FIFO), ensuring we process level by level.
def dfs_iterative(root):
if not root:
return []
result = []
stack = [root] # Stack for DFS
while stack:
node = stack.pop() # LIFO: remove from end
result.append(node.val)
# Add children to stack (right first, so left is processed first)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
Key: pop() removes from end (LIFO), ensuring we go deep before going wide.
def dfs_recursive(root):
result = []
def traverse(node):
if not node:
return
result.append(node.val) # Pre-order
traverse(node.left) # Recurse left
traverse(node.right) # Recurse right
traverse(root)
return result
The call stack naturally implements LIFO behavior! Each recursive call adds to the stack.
| Metric | BFS | DFS |
|---|---|---|
| Time Complexity | O(n) | O(n) |
| Space (Worst) | O(w) - max width | O(h) - max height |
| Best for Shortest Path | Yes | No |
| Memory (Balanced Tree) | O(n/2) ≈ O(n) | O(log n) |
Key insight: For a balanced tree, DFS uses less memory (O(log n) vs O(n)) because it only stores one path at a time, while BFS stores an entire level.
Continue Learning
Level 1
Learn BFS vs DFS through a maze exploration analogy. Discover when to use each strategy.
Author
Mr. Oz
Duration
5 mins
Level 2
Implementation details, queue vs stack usage, and production-ready code examples.
Author
Mr. Oz
Duration
8 mins
Level 3
Memory layout, CPU cache performance, and real-world optimization techniques.
Author
Mr. Oz
Duration
12 mins