Binary Tree Level Order Traversal - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

We solve this problem using a Breadth-First Search (BFS) traversal, which visits all nodes at the same level before moving to the next level. BFS uses a queue (FIFO) to ensure nodes are processed in left-to-right order, since children are enqueued in the same order they should appear in the next level (left first, then right).

  • Base case: If the root is null, return an empty array β€” there are no levels to traverse.
  • Initialization: Enqueue the root node and prepare an empty 2D array result to store the values level by level.
  • Iterative processing: Continue while the queue is not empty (while (!queue.isEmpty())):
    1. At the start of each iteration, take a snapshot of the queue size into a variable levelSize. This represents the number of nodes that belong to the current level. ⚠️ We take this snapshot before processing any nodes because, as we dequeue nodes and enqueue their children, the queue size may change, affecting which nodes belong to this level. Also, initialize an empty array levelValues to begin collecting the node values for this level in their correct left-to-right order.
    2. Using this levelSize snapshot, process exactly that many nodes β€” these are all the nodes for the current level. For each dequeued node:
      • Record its value for this level by pushing it into the levelValues array.
      • Enqueue its children (left first, then right) for the next iteration, which will handle the next level.
    3. After processing all levelSize nodes, push the collected level values (levelValues) into result.

πŸ“Œ Why it works

The queue ensures that we always process nodes level by level and in left-to-right order because:

  • Children are enqueued in the same order they should appear in the next level (left first, then right).
  • Each iteration processes exactly one level’s nodes, determined by the levelSize snapshot taken at the start.

Return value: result, a 2D array where each inner array contains the node values of one level, processed from left to right per iteration.

Time Complexity

O(n), where n is the number of nodes β€” each node is enqueued and dequeued exactly once.

Space Complexity

O(w) excluding the output β€” where w is the maximum width of the tree (for the queue), which in the worst case can be O(n/2). The output itself also requires O(n) space, where n is the total number of nodes.

Visucodize editorial solution titled JS Solution for LeetCode's Binary Tree Level Order Traversal coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/binary-tree-level-order-traversal.