ToolMight Logo
MediumTrees & BSTBreadth-First Search (BFS)Queue Level Batching

Binary Tree Level Order Traversal

Group binary tree node values level-by-level from left to right. Compare FIFO queue level batching against depth-indexed DFS recursion.

Optimal Time
O(n)
Optimal Space
O(w)
Primary Pattern
Breadth-First Search (BFS)
Visualizer
Open Interactive View →

Problem Statement

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Examples & Constraints

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Explanation: Level 0 has node 3. Level 1 has nodes 9 and 20. Level 2 has nodes 15 and 7.
Example 2
Input: root = []
Output: []
Explanation: Empty tree produces an empty list.
Constraints
  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Pattern Recognition & Core Invariant

How to Spot This Pattern

Grouping tree nodes by depth or shortest step count from the root maps directly to FIFO queue BFS capturing levelSize per round.

Core Invariant

Measuring levelSize = queue.length before popping drains guarantees all nodes popped during that loop share the same depth while queued children belong strictly to depth + 1.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. BFS with Queue Level Size SnapshotOptimal
O(n)O(w)Use 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.
2. Recursive DFS with Depth Buckets
O(n)O(h)Pass the current node depth down a pre-order DFS traversal and append each value directly into res[depth].

1. BFS with Queue Level Size Snapshot

Optimal
TimeO(n)
SpaceO(w)

Use 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.

Time ComplexityO(n)

Every node in the tree of size N is enqueued and dequeued exactly once.

Space ComplexityO(w)

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:

  1. If the tree is empty (root == null), return an empty list [].
  2. Push root into a FIFO queue.
  3. 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 levelSize times:
  • Pop a node curr = queue.pop().
  • Append curr.val to currentLevel.
  • If curr.left exists, push it into the queue.
  • If curr.right exists, push it into the queue.
  • Append currentLevel to the final result list res.
  1. 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

Execution Trace·Step 1 of 4
1Level 0 (Root)

Queue contains [3]. levelSize = 1. Pop 3. Push children 9 and 20. level = [3].

State:res = [[3]]queue = [9, 20]
Strengths
  • +Optimal linear O(n) runtime
  • +Clean level isolation using queue.size() without extra level counters
Trade-offs
  • -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.

File: solution.py
Python
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def 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 res
if __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))

2. Recursive DFS with Depth Buckets

TimeO(n)
SpaceO(h)

Pass the current node depth down a pre-order DFS traversal and append each value directly into res[depth].

Time ComplexityO(n)

Visits every node in the tree once.

Space ComplexityO(h)

Call stack consumes depth H frames (excluding result list), using O(log n) on balanced trees.

How It Works

Level Ordering Without a Queue

If you visit left subtrees before right subtrees (standard pre-order traversal: Node -> Left -> Right), every node at a given depth d is visited strictly left-to-right!

  1. Maintain res = [].
  2. Recurse dfs(node, depth):
  • If node == null, return.
  • If depth == res.length, append a new bucket [].
  • Push node.val into res[depth].
  • Recurse dfs(node.left, depth + 1), then dfs(node.right, depth + 1).

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Visit Root (3) at depth 0

depth 0 == len(res). Allocate bucket [3]. Recurse left to 9 with depth 1.

State:res = [[3]]
Strengths
  • +Shorter recursive code
  • +O(log n) auxiliary stack space on balanced trees vs O(n) queue breadth
Trade-offs
  • -Can stack-overflow on deeply skewed chains (2,000+ levels)

Reference Implementation

Complete implementation for Recursive DFS with Depth Buckets in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def level_order_dfs(root):
res = []
def dfs(node, depth):
if not node:
return
if depth == len(res):
res.append([])
res[depth].append(node.val)
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root, 0)
return res
Interactive Visualizer

Trace Tree Traversals mechanics in memory

Step through custom inputs in the Tree Traversals visualizer to inspect pointer updates, array shifts, and call-stack state alongside Binary Tree Level Order Traversal.

Open Tree Traversals visualizer

Frequently Asked Questions

How does recording queue size isolate each level?

Capturing levelSize = queue.length before popping nodes fixes the exact count for the current tier. Newly enqueued children are pushed to the back and wait for the next outer loop cycle.

Can we do level order traversal using DFS instead of a Queue?

Yes. Passing depth in pre-order DFS appends into res[depth], visiting left children before right children so every level ends up ordered left-to-right.

Why is `queue.shift()` in JavaScript slower than an explicit queue/index?

For up to 2,000 nodes Array.shift() passes easily, while for huge trees advancing a head read index or deque avoids O(W) array shifting per dequeue.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Empty tree (root === null) returns an empty array [].
  • Single root node returns [[val]].
  • Left-only or right-only skewed chain of 2000 nodes produces [[n1], [n2], ...]; iterative BFS avoids 2000-deep recursion frames.

Common Bugs to Avoid

  • Writing `for (let i = 0; i < queue.length; i++)` instead of storing `const levelSize = queue.length` beforehand — pushing children alters queue.length dynamically and mixes levels.
  • Forgetting to check `root === null` before pushing onto the queue, producing `[null]` crashes.
  • Popping right-child before left-child on standard left-to-right BFS.

Interview Follow-Up Variations

  • Binary Tree Zigzag Level Order Traversal: reverse every odd-depth level slice or write from the back of a pre-sized level array.
  • Binary Tree Right Side View: capture the last element popped on every BFS level (`i === levelSize - 1`).
  • Binary Tree Level Order Traversal II: append bottom-up or reverse the level buckets at the end.

Related Problems

All problems
EasyTrees & BST

Maximum Depth of Binary Tree

Compute the maximum depth (node count along longest root-to-leaf path) of a binary tree using recursive post-order DFS and iterative level-order BFS.

Pattern: Depth-First Search (DFS)
O(n) · O(h)
Solve
EasyTrees & BST

Invert Binary Tree

Mirror a binary tree around its vertical axis by swapping left and right child pointers via recursive DFS or iterative level-order BFS.

Pattern: DFS Traversal
O(n) · O(h)
Solve
EasyTrees & BST

Subtree of Another Tree

Check whether subRoot matches an entire subtree of root in structure and values. Compare double-DFS tree matching against O(n + m) pre-order serialization + substring search.

Pattern: Tree Traversal DFS
O(n * m) · O(h)
Solve