Sign inEnroll free
DSA Visualizer · 25 visualizationsBinary Tree Level Order
MediumTrees & BFS

Binary Tree Level Order

Given the root of a binary tree, return the level order traversal of its nodes' values (left to right, level by level). Use a queue (BFS): process all nodes at the current level before moving to the next. Track level size to group nodes correctly.

The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n) · space O(n)
from collections import deque

def levelOrder(root) -> list[list[int]]:
    if not root:
        return []
    result, queue = [], deque([root])
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.popleft()
            level.append(node.val)
            if node.left:  queue.append(node.left)
            if node.right: queue.append(node.right)
        result.append(level)
    return result
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough