Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Level Order Sum

LeetCode #1161Medium
Sum each level with the level-batching loop

Given the root of a binary tree where the root is level 1 and each level below increments by one, return the smallest level number whose nodes have the largest sum of values.

Asked atAmazon
step 1 / 14
binary tree
9
3
15
20
7
queue (FIFO)
front →
(empty)
← back
BFS by level
1levelSums(root):
2 queue = [root]
3 while queue not empty:
4 levelSize = len(queue)
5 sum = 0
6 for _ in range(levelSize):
7 node = queue.dequeue()
8 sum += node.val
9 enqueue node.children
10 levelSums.append(sum)
11 return levelSums // max() for heaviest level
state
  • targetsum per level

line 1Goal: the SUM of the node values on each level — and from those, the heaviest level. This is the level-batching loop with a single accumulator added: dequeue a whole level, add each value into a running sum, then record that sum and reset.