Problem statement

https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/

Solution

Variation of Leetcode 0102. Binary Tree Level Order Traversal.

Complexity

It is O(n) for time and space.

Code

class Solution:
    def maxLevelSum(self, root):
        if not root: return 0
        queue = deque([root])
        result = []
        while queue:
            level = []
            for i in range(len(queue)):
                node = queue.popleft()
                level.append(node.val)
                if node.left:  queue.append(node.left)
                if node.right: queue.append(node.right)
            result.append(sum(level))
        return result.index(max(result)) + 1