1. BFS with Queue Level Size Snapshot
OptimalUse a FIFO queue. At each level, record the queue size and drain exactly that many nodes into a level list while enqueuing their children in O(n) time.
Every node in the tree of size N is enqueued and dequeued exactly once.
Consumes memory proportional to the maximum breadth W of the tree stored in the queue (at most N/2 nodes for a full balanced binary tree).
How It Works
The Core Mental Model: Level-by-Level Flushing
Standard Breadth-First Search (BFS) processes nodes in order of distance from the root using a queue. But how do we know which nodes belong to which level?
The key insight is the Queue Size Snapshot:
- If the tree is empty (
root == null), return an empty list[]. - Push
rootinto a FIFO queue. - While the queue is not empty:
- Capture
levelSize = queue.size(). This is the exact number of nodes that belong exclusively to the current horizontal level! - Create an empty list
currentLevel. - Loop exactly
levelSizetimes: - Pop a node
curr = queue.pop(). - Append
curr.valtocurrentLevel. - If
curr.leftexists, push it into the queue. - If
curr.rightexists, push it into the queue. - Append
currentLevelto the final result listres.
- When the queue is empty, return
res.
Why the Queue Size Snapshot Guarantees Isolation
Even though child nodes for the next level are being pushed into the queue during the loop, our loop only runs levelSize times (which was measured before any children were pushed). This guarantees complete separation between consecutive horizontal tiers!
Step-by-Step Dry Run
Queue contains [3]. levelSize = 1. Pop 3. Push children 9 and 20. level = [3].
res = [[3]]queue = [9, 20]- +Optimal linear O(n) runtime
- +Clean level isolation using queue.size() without extra level counters
- -Consumes queue memory proportional to the widest level of the tree
Reference Implementation
Complete implementation for BFS with Queue Level Size Snapshot in Python, JavaScript, Java, C++, and C.
from collections import dequeclass TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightdef level_order(root: TreeNode | None) -> list[list[int]]:if not root:return []res = []queue = deque([root])while queue:level_size = len(queue)current_level = []for _ in range(level_size):node = queue.popleft()current_level.append(node.val)if node.left:queue.append(node.left)if node.right:queue.append(node.right)res.append(current_level)return resif __name__ == "__main__":# Tree: [3, 9, 20, null, null, 15, 7]root = TreeNode(3)root.left = TreeNode(9)root.right = TreeNode(20, TreeNode(15), TreeNode(7))print("Level Order:", level_order(root))
function TreeNode(val, left, right) {
this.val = (val === undefined ? 0 : val);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
function levelOrder(root) {
if (!root) return [];
const res = [];
const queue = [root];
while (queue.length > 0) {
const levelSize = queue.length;
const currentLevel = [];
for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
currentLevel.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
res.push(currentLevel);
}
return res;
}
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20, new TreeNode(15), new TreeNode(7));
console.log("Level Order:", levelOrder(root));import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Solution {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
currentLevel.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
res.add(currentLevel);
}
return res;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20, new TreeNode(15), new TreeNode(7));
System.out.println("Level Order: " + levelOrder(root));
}
}#include <iostream>
#include <vector>
#include <queue>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* l, TreeNode* r) : val(x), left(l), right(r) {}
};
std::vector<std::vector<int>> levelOrder(TreeNode* root) {
std::vector<std::vector<int>> res;
if (!root) return res;
std::queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int levelSize = q.size();
std::vector<int> currentLevel;
for (int i = 0; i < levelSize; i++) {
TreeNode* node = q.front();
q.pop();
currentLevel.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(currentLevel);
}
return res;
}
int main() {
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(9);
root->right = new TreeNode(20, new TreeNode(15), new TreeNode(7));
std::vector<std::vector<int>> result = levelOrder(root);
for (const auto& level : result) {
std::cout << "[";
for (int val : level) std::cout << val << " ";
std::cout << "]\n";
}
return 0;
}#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// Simple level-order print
void printLevelOrder(struct TreeNode* root) {
if (!root) return;
struct TreeNode* queue[2000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
int levelSize = rear - front;
printf("[");
for (int i = 0; i < levelSize; i++) {
struct TreeNode* node = queue[front++];
printf("%d%s", node->val, i < levelSize - 1 ? " " : "");
if (node->left) queue[rear++] = node->left;
if (node->right) queue[rear++] = node->right;
}
printf("]\n");
}
}
int main(void) {
struct TreeNode* root = createNode(3);
root->left = createNode(9);
root->right = createNode(20);
root->right->left = createNode(15);
root->right->right = createNode(7);
printLevelOrder(root);
return 0;
}