AlgoViz

Level Order Sum

Medium

Process one whole level per queue pass

Problem

Given a binary tree, return a list with the sum of node values at each level (top to bottom).

In simple words

BFS level by level, adding up the values on each row.

The idea

Record the queue's size before each pass and pop exactly that many nodes — those are precisely one level. Summing them as you go gives one total per level, and the same size-snapshot trick underlies every level-aware BFS.

The trick

  • Snapshot `queue.size()` before the inner loop or you will bleed into the next level.
  • Children pushed during a pass belong to the next level, never the current one.
123456

Step 1 of 5. Level-order BFS: snapshot the queue size to process exactly one level per iteration.

1/5
Optimal
timeO(n)spaceO(n)

Fix the level width up front.

1const q = [root], out = [];2while (q.length) {3  const level = [];4  for (let n = q.length; n > 0; n--) {5    const node = q.shift();6    level.push(node.val);7    if (node.left) q.push(node.left);8    if (node.right) q.push(node.right);9  }10  out.push(level);11}

Input

nodes
6, 5 edges

Memory

levels

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
tree = [1,2,3,4,5]
Output:
[1, 5, 9]
Explanation:
Sum each level: 1, then 2+3, then 4+5.

Example 2

Input:
tree = [10,20,30]
Output:
[10, 50]
Explanation:
10, then 50.

Example 3

Input:
tree = [5]
Output:
[5]
Explanation:
One level.

Finished the walkthrough? Add it to your streak.