#1161

Maximum Level Sum of a Binary Tree

Medium
TreeDepth-First SearchBreadth-First SearchBinary TreeBreadth-First SearchLevel Order Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use a breadth-first search (BFS) approach to traverse the tree level by level while calculating the sum of node values at each level. This is efficient as we only traverse each node once.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue for BFS and add the root node.
  2. 2Step 2: For each level, calculate the sum of node values and track the maximum sum and corresponding level.
  3. 3Step 3: Return the level with the maximum sum.
solution.py30 lines
1# Full working Python code
2from collections import deque
3class TreeNode:
4    def __init__(self, val=0, left=None, right=None):
5        self.val = val
6        self.left = left
7        self.right = right
8
9def maxLevelSum(root):
10    if not root:
11        return 0
12    queue = deque([root])
13    max_sum = float('-inf')
14    level = 0
15    max_level = 0
16    while queue:
17        level += 1
18        level_sum = 0
19        for _ in range(len(queue)):
20            node = queue.popleft()
21            level_sum += node.val
22            if node.left:
23                queue.append(node.left)
24            if node.right:
25                queue.append(node.right)
26        if level_sum > max_sum:
27            max_sum = level_sum
28            max_level = level
29    return max_level
30

Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the queue used for BFS, which can hold up to n nodes in the worst case.

  • 1Using BFS allows us to efficiently calculate level sums without redundant calculations.
  • 2Tracking the maximum sum and its level during traversal helps avoid a second pass.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.