Problem Description
Given the root of a binary tree, determine the smallest level (starting from 1) with the maximum sum of node values. In other words, compute the sum of every level's nodes and return the level number where the sum is maximized.
Key Insights
- Use a level order traversal (BFS) to process the tree by levels.
- Maintain a running sum for each level and update the maximum sum when a higher level sum is encountered.
- Track the current level and record the level number whenever a new maximum sum is found.
- Since the first occurrence of the maximum sum is needed when sums are equal, only update on strictly greater sums.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the tree (each node is visited once).
Space Complexity: O(m), where m is the maximum number of nodes stored at any level (this can be O(n) in the worst-case scenario of a balanced tree).
Solution
Perform a breadth-first search (BFS) on the binary tree using a queue to traverse the tree level by level. For each level, calculate the sum of nodes and compare it against the maximum sum recorded so far. If the current level's sum exceeds the previous maximum, update the maximum sum and note the level number. This approach naturally handles the requirement to return the smallest level with the maximum sum since levels are processed sequentially.