Binary Tree · Traversal

Level Order Traversal

Visit nodes level by level using BFS. Group each depth into its own result array.

QueueBFSLevel Grouping

Key concepts at a glance — for those who already know the basics.

Problem Statement

Binary Tree Level Order Traversal

Given the root of a binary tree, return level by level traversal as nested lists.
Example 1

Input: root = [1, null, 2, 3]

Output: [[1], [2], [3]]

Each depth becomes one array in result.

Example 2

Input: root = [1, 2, 3, 4, 5, 6, 7]

Output: [[1], [2, 3], [4, 5, 6, 7]]

Classic BFS output grouped by level.

Constraints

  • The number of nodes is in range [0, 100].
  • Each node value is in range [-100, 100].
01

The Rule

Level by Level using Queue

Freeze current queue size, process exactly that many nodes, then move to the next level.

02

How to Think

1

Push root into queue

This starts BFS from top of tree.

2

Read level size before popping

That number defines the boundary of current level.

3

Collect values and enqueue children

Children naturally become the queue for next level.

03

Code

solution.py
from collections import deque
def levelOrder(root):
if not root: return []
ans = []
q = deque([root])
while q:
level_size = len(q)
level = []
for _ in range(level_size):
node = q.popleft()
level.append(node.data)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
ans.append(level)
return ans
04

Complexity

Time

O(n)

Each node is processed once.

Space

O(w)

Queue can hold the widest level.

05

Interview Uses

Level based metrics

Count nodes per depth or compute level averages with the same BFS skeleton.

Zigzag traversal

Use level order and alternate insertion direction on every level.

Bottom up traversal

Collect level order then reverse once at the end.

Tree views

Left view and right view are level order with first or last pick per level.

Ready to see it in action?

Step through the visualizer to watch the algorithm state update live.

Open Visualizer