Browse curriculum

Maximum Level Sum of a Binary Tree

Maximum Level Sum of a Binary Tree: sum every level with BFS and return the smallest level with the largest sum.

Medium
10 min
Solve on LeetCode

Examples

Input:root = [1,7,0,7,-8,null,null]
Output:2
Explain:

Level 1 sums to 1, level 2 to 7, level 3 to -1.

Input:root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output:2
Explain:

Level sums are 989, 10250, 9305 and -32127.

Problem Understanding

Given the root of a binary tree, the root is on level 1, its children on level 2, and so on (LeetCode 1161).

  • Goal: Return the smallest level whose values add up to the largest sum.
  • Example: [1, 7, 0, 7, -8] has level sums 1, 7 and -1, so the answer is level 2.

The same loop answers the other per-level questions (averages, maximums) by changing only what is accumulated.

Algorithm Strategy

Use level-order BFS.

  1. Start: best_sum at negative infinity, best_level = 1, level = 1, and the root in the queue.
  2. One level per pass: set level_sum = 0, read size, then dequeue exactly size nodes, adding each value and enqueueing its children.
  3. Compare: after the inner loop, replace the best only if level_sum > best_sum. A tie keeps the earlier level, which is the smallest one: exactly what the problem asks for.
  4. Advance: level += 1, and repeat until the queue is empty. Return best_level.

Interactive Visualization

LEVELS COUNT FROM 1 · GREEN = ADDED TO THIS LEVEL'S SUM

best_sum = −∞

level 1 sum

0

best_sum

−∞

best_level

1

queue (front first)

Empty

level sums

No level finished yet

 

best_sum = −∞, best_level = 1, level = 1

Next

Put the root, 1, in the queue

Free preview: the first 8 of 26 steps

Tree

The level being summed is outlined as it waits in the queue and turns green as each value is added. After every level the sum is compared with the best so far: try the Tie preset, where two levels sum to the same value and the earlier one is kept.

Dry Run

Tree: [1, 7, 0, 7, -8]: root 1; children 7 and 0; 7 has children 7 and -8.

Level Nodes Sum Calculation Action
1 [1] sum = 1 Max Sum so far: 1 (Level 1).
2 [7, 0] sum = 7 + 0 = 7 Max Sum: 7 (Level 2).
3 [7, -8] sum = 7 + (-8) = -1 Max Sum: 7 (Level 2).

Result: Level 2 has the Maximum Sum.

Edge Cases & Common Mistakes

Edge Cases:

  • Ties: Use a strict >. Replacing on >= would return the deepest of the tied levels, not the smallest.
  • All-negative levels: Starting best_sum at 0 would never be beaten by a negative level. Start at negative infinity (Long.MIN_VALUE, LLONG_MIN).
  • Large sums: LeetCode allows up to 10,000 nodes with values up to 100,000 in size, so a level sum stays within ±10^9 and fits in 32 bits. The Java, C++ and C code keeps sums in 64-bit integers anyway, so best_sum can start below every possible level sum.

Common Mistakes:

  • Setting level_sum = 0 once before the loop instead of at the start of every level, which turns it into one running total for the whole tree.
  • Numbering levels from 0: LeetCode counts the root as level 1.

Solution Code

Finding the Level with Maximum Sum.

Maximum Level Sum of a Binary Tree Code
1var maxLevelSum = function(root) {
2 let bestSum = -Infinity;
3 let bestLevel = 1;
4 let level = 1;
5 const queue = [root];
6 let head = 0;
7 while (head < queue.length) {
8 let levelSum = 0;
9 const size = queue.length - head;
10 for (let i = 0; i < size; i++) {
11 const node = queue[head++];
12 levelSum += node.val;
13 if (node.left) {
14 queue.push(node.left);
15 }
16 if (node.right) {
17 queue.push(node.right);
18 }
19 }
20 if (levelSum > bestSum) {
21 bestSum = levelSum;
22 bestLevel = level;
23 }
24 level++;
25 }
26 return bestLevel;
27};

Maximum Level Sum of a Binary Tree in Python, Java, C++, TypeScript and C

Maximum Level Sum of a Binary Tree in Python
from collections import deque


class Solution:
    def maxLevelSum(self, root: Optional[TreeNode]) -> int:
        best_sum = float('-inf')
        best_level = 1
        level = 1
        queue = deque([root])
        while queue:
            level_sum = 0
            size = len(queue)
            for _ in range(size):
                node = queue.popleft()
                level_sum += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            if level_sum > best_sum:
                best_sum = level_sum
                best_level = level
            level += 1
        return best_level
Maximum Level Sum of a Binary Tree in Java
class Solution {
    public int maxLevelSum(TreeNode root) {
        long bestSum = Long.MIN_VALUE;
        int bestLevel = 1;
        int level = 1;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            long levelSum = 0;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                levelSum += node.val;
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            if (levelSum > bestSum) {
                bestSum = levelSum;
                bestLevel = level;
            }
            level++;
        }
        return bestLevel;
    }
}
Maximum Level Sum of a Binary Tree in C++
class Solution {
public:
    int maxLevelSum(TreeNode* root) {
        long long bestSum = LLONG_MIN;
        int bestLevel = 1;
        int level = 1;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            long long levelSum = 0;
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode* node = q.front();
                q.pop();
                levelSum += node->val;
                if (node->left) {
                    q.push(node->left);
                }
                if (node->right) {
                    q.push(node->right);
                }
            }
            if (levelSum > bestSum) {
                bestSum = levelSum;
                bestLevel = level;
            }
            level++;
        }
        return bestLevel;
    }
};
Maximum Level Sum of a Binary Tree in TypeScript
function maxLevelSum(root: TreeNode | null): number {
    let bestSum = -Infinity;
    let bestLevel = 1;
    let level = 1;
    const queue: TreeNode[] = [root!];
    let head = 0;
    while (head < queue.length) {
        let levelSum = 0;
        const size = queue.length - head;
        for (let i = 0; i < size; i++) {
            const node = queue[head++];
            levelSum += node.val;
            if (node.left) {
                queue.push(node.left);
            }
            if (node.right) {
                queue.push(node.right);
            }
        }
        if (levelSum > bestSum) {
            bestSum = levelSum;
            bestLevel = level;
        }
        level++;
    }
    return bestLevel;
}
Maximum Level Sum of a Binary Tree in C
#include <limits.h>

int maxLevelSum(struct TreeNode* root) {
    long long bestSum = LLONG_MIN;
    int bestLevel = 1;
    int level = 1;
    struct TreeNode** queue = malloc(10000 * sizeof(struct TreeNode*));
    int head = 0, tail = 0;
    queue[tail++] = root;
    while (head < tail) {
        long long levelSum = 0;
        int size = tail - head;
        for (int i = 0; i < size; i++) {
            struct TreeNode* node = queue[head++];
            levelSum += node->val;
            if (node->left) {
                queue[tail++] = node->left;
            }
            if (node->right) {
                queue[tail++] = node->right;
            }
        }
        if (levelSum > bestSum) {
            bestSum = levelSum;
            bestLevel = level;
        }
        level++;
    }
    free(queue);
    return bestLevel;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start the best

    Set best_sum to negative infinity, best_level and level to 1, and enqueue the root.

  2. Sum one level

    Reset level_sum, dequeue exactly the level's nodes, add their values and enqueue their children.

  3. Keep the best level

    If level_sum is strictly greater than best_sum, record it and the level; then move to the next level.

Frequently asked questions

Why compare with > instead of >=?

The problem asks for the smallest level when several share the largest sum. Replacing the best only on a strictly larger sum keeps the earliest of the tied levels.


Why start best_sum at negative infinity?

Every level could sum to a negative number. Starting at 0 would mean no level ever beats the start, and the answer would stay at level 1 even when a later level is larger.


How would I compute level averages instead?

Keep the same loop and divide each level's sum by its size after the inner loop. Only what is accumulated per level changes; the queue logic stays the same.

New to the technique behind this problem? Watch it run step by step:

Breadth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description