Leetcode 1116 Solution

This article provides solution to leetcode question 1116 (maximum-level-sum-of-a-binary-tree)

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

Solution

# 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:
        level = 1
        q = collections.deque()
        q.append(root)

        ans = (-sys.maxsize, -sys.maxsize)

        while q:
            s = len(q)

            level_sum = 0

            for _ in range(s):
                node = q.popleft()

                level_sum += node.val

                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)

            ans = max(ans, (level_sum, -level))

            level += 1

        return -ans[1]