Skip to main content

Level-Order Wave Sum

medium
QueueTreeBinary TreeBreadth First SearchBfs Level Order
Asked atAmazonMicrosoftMetaGoogleBloomberg

Problem Description

You are given the root of a binary tree. Perform a **level-order (BFS) traversal** and return the **sum of node values at each level** as an array, where the result array's `i`-th element is the total of all values on level `i` (0-indexed from the root).

**Example 1:**
```
Input: root = [5, 3, 8, 1, 4, 7, 9]

5
/ \
3 8
/ \ / \
1 4 7 9

Output: [5, 11, 21]
Explanation:
Level 0: 5 → sum = 5
Level 1: 3 + 8 → sum = 11
Level 2: 1 + 4 + 7 + 9 → sum = 21
```

**Example 2:**
```
Input: root = [1, 2, 3, null, 5]

1
/ \
2 3
\
5

Output: [1, 5, 5]
Explanation:
Level 0: 1
Level 1: 2 + 3 = 5
Level 2: 5
```

Constraints

  • The number of nodes in the tree is in the range [0, 10^4]
  • -10^4 <= Node.val <= 10^4
  • The tree is a valid binary tree (no cycles)

Follow-up

Instead of sums, return the **average** (mean) value at each level as a list of doubles.

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.

CodeBrainery

A technical blogging platform for developers and engineers to share knowledge and connect.

Connect

© 2026 Kodetra Technologies Pvt. Ltd. All rights reserved. CodeBrainery is a product of Kodetra Technologies Pvt. Ltd.