Maximum Level Sum of a Binary Tree — LeetCode 1161 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#1161
Reading time
5 min

The problem

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal.

Example

Input
root = [1,7,0,7,-8,null,null]
Output
2
Explanation
Level 1 sum = 1.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxLevelSum(self, root: Optional[TreeNode]) -> int:
        q = deque([root])
        mx = -inf
        i = 0
        while q:
            i += 1
            s = 0
            for _ in range(len(q)):
                node = q.popleft()
                s += node.val
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            if mx < s:
                mx = s
                ans = i
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the binary tree auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1161. Maximum Level Sum of a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 1161. Maximum Level Sum of a Binary Tree?
LeetCode 1161. Maximum Level Sum of a Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 1161. Maximum Level Sum of a Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1161. Maximum Level Sum of a Binary Tree?
The Python solution on this page uses O(n), where n is the number of nodes in the binary tree auxiliary space.
What topics does LeetCode 1161. Maximum Level Sum of a Binary Tree cover?
LeetCode 1161. Maximum Level Sum of a Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview