Below is a pattern-focused breakdown of DFS, BFS, and Heap usage tailored for LeetCode-style problems. This is structured for pattern recognition → template → when to use → example problems.
DFS Patterns (Trees & Graphs)
Core Idea
- Go deep first, then backtrack
- Uses recursion (stack) or explicit stack
- Good for exploring all possibilities
Simple Traversal (Tree DFS)
Use When
- Visit all nodes
- Compute something (sum, depth, etc.)
Template
def dfs(node):
if not node:
return
# process node
dfs(node.left)
dfs(node.right)
Variations
- Preorder → process before recursion
- Inorder → process between
- Postorder → process after
Problems
- Max Depth of Binary Tree
- Same Tree
- Subtree of Another Tree