Level Order Sum

25 min · levelOrderSum()
easy

An org chart tells a clearer story when you total one row at a time: the director, then every manager, then every person reporting below them.

Given the root of a binary tree, return one sum for each depth — the number of edges from the root to a node. Entry i in your answer must contain the sum of every node at depth i; the root sits at depth 0.

A few ground rules:

  • Keep the sums ordered from the root downward.
  • Include negative values exactly as they are.
  • An empty tree has no depths, so return [].

Constraints

  • 0 <= node count <= 10_000
  • -1_000 <= node.val <= 1_000
  • Every level sum fits in a signed 32-bit integer.

Hints

Tag each depth

A depth-first walk can carry the current depth beside every node. Grow a sums array when you reach a depth for the first time, then add the node's value to that bucket.

Process a whole row

A queue visits nodes in level order. Before processing a level, save the queue's current length — that many nodes belong to the same sum.

Don't mix the next level in

Children enter the back of the queue while you read the current level. Process only the saved number of nodes before appending the sum.

Follow-up

Could you produce the same sums with depth-first traversal? Which tree shape makes that version hold the most pending work?

Visible cases

Examples

Example 1

ready
Input
root = [
  3,
  9,
  20,
  null,
  null,
  15,
  7
]
Expected
[
  3,
  29,
  22
]
Why
the three depths sum to 3, 29, and 22

Example 2

ready
Input
root = []
Expected
[]
Why
an empty tree has no level sums

Example 3

ready
Input
root = [
  1
]
Expected
[
  1
]
Why
the root is the only value at depth 0

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite