The Problem

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

The tree is given as an array in level-order format, where null represents a missing node. Return a list of lists, where each inner list contains the values of nodes at that depth level.

Interactive Visualization

Speed:
Tree Visualization
BFS Queue (front โ†’ back)
Empty
Result
[]
Code
fun levelOrder(root: TreeNode?): List<List<Int>> {    if (root == null) {        return emptyList()    }    val result = mutableListOf<List<Int>>()    val queue: ArrayDeque<TreeNode> = ArrayDeque()    queue.add(root)    while (queue.isNotEmpty()) {        val levelSize = queue.size        val level = mutableListOf<Int>()        for (i in 0 until levelSize) {            val node = queue.removeFirst()            level.add(node.`val`)            node.left?.let { queue.add(it) }            node.right?.let { queue.add(it) }        }        result.add(level)    }    return result}
Status
Press Step or Play to begin.

How It Works

Key Insight

Level order traversal processes a tree breadth-first โ€” visiting all nodes at depth 0, then all at depth 1, and so on. A queue naturally gives us this order: we enqueue children as we process parents. The trick is tracking where one level ends and the next begins by capturing len(queue) at the start of each level.

The Algorithm

  • Initialize: Create a queue with the root node. Create an empty result list.
  • Outer loop: While the queue is not empty, a new level begins.
  • Capture level size: level_size = len(queue) โ€” this is how many nodes are at the current level.
  • Inner loop: Process exactly level_size nodes from the front of the queue.
  • For each node: Dequeue it, record its value, then enqueue its left and right children (if they exist).
  • After the inner loop: Append the collected level values to the result.
  • Repeat until the queue is empty โ€” all levels have been processed.

Complexity

Time O(n)
Space O(n)

Every node is enqueued and dequeued exactly once, giving O(n) time. The queue holds at most one full level of the tree at a time โ€” in a complete binary tree the last level has ~n/2 nodes, so space is O(n).