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.

1. DFS Patterns (Trees & Graphs)

Core Idea

Pattern 1: Simple Traversal (Tree DFS)

Use When

Template

def dfs(node):

if not node:

return

process node

dfs(node.left)

dfs(node.right)

Variations