🔵

Standard BFS — Level Order

Enqueue the root, mark it visited. Each outer loop iteration drains one full level — poll every node in the current batch, enqueue their unvisited children. First time a node is reached = shortest distance. Expand like ripples in water, level by level.

Shortest Path Level Order Tree / Graph Time O(V+E) Space O(V)
📋 When to Use
  • Find shortest path in unweighted graph or tree
  • Level-order traversal — process nodes depth by depth
  • Find nodes exactly k steps from root or any node
  • Right side view, zigzag level order, average of levels
  • Cycle detection — revisit check in general graphs
💡 Key: snapshot size = queue.size() at the start of each outer loop. That snapshot is exactly one level — process only those nodes before incrementing the level counter.
⚡ Complexity
Time
O(V+E)
Space
O(V)
Every node enqueued/dequeued at most once. The visited set prevents revisits. Max queue size = widest level of the tree (O(n/2) for perfect binary tree). Stack depth = O(1) — no recursion.
Live Animation · Standard BFS · LC #102
Problem Given a binary tree with 8 nodes (root = 1, 4 levels), return all nodes grouped by level. Use a queue and snapshot int size = queue.size() at the start of each outer loop — that count is exactly one level to process before incrementing the level counter.
Input: root = [1,2,3,4,5,6,null,7,8] · Answer: [[1],[2,3],[4,5,6],[7,8]]
Step 1 / 1
📥 Enqueue ⚙️ Process 🌊 Level Done ✅ Complete
Binary Tree — root = 1
L0 L1 L2 L3 1 d=? 2 d=? 3 d=? 4 d=? 5 d=? 6 d=? 7 d=? 8 d=?
Level 0
Level 1
Level 2
Level 3
Processing
🗂️ Queue
front = next to process
empty
Stats
🌊 level = 0
✅ visited = 0
📋 q.size = 0
Press ▶ Play or Next ▶ to begin
Queue<Integer> q = new LinkedList<>(); q.offer(root); visited.add(root);
☕ Java Pattern Skeleton Java 8
// Standard BFS — Level Order (works for tree or graph)
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int level = 0;

while (!queue.isEmpty()) {
    int size = queue.size();          // snapshot — one full level
    for (int k = 0; k < size; k++) {
        TreeNode node = queue.poll();  // process at distance = level
        if (node.left  != null) queue.offer(node.left);
        if (node.right != null) queue.offer(node.right);
    }
    level++;                           // full level done
}
🎯 Practice Problems