leetcode - 1161. Maximum Level Sum of a Binary Tree

Description

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 1:

Input: root = [1,7,0,7,-8,null,null]
Output: 2
Explanation: 
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.

Example 2:

Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]
Output: 2

Constraints:

The number of nodes in the tree is in the range [1, 104].
-10^5 <= Node.val <= 10^5

Solution

Basic level order of traversal. Remember how to keep track of the level of the tree.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( log ⁡ n ) o(\log n) o(logn), use the queue to store all the node in the same level.

Code

# 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:
        import collections
        rightest_node = root
        queue = collections.deque([root])
        sum_level = {}
        level = 1
        level_sum = 0
        max_level_sum = -100000
        res = 0
        while queue:
            node = queue.popleft()
            level_sum += node.val
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
            if node == rightest_node:
                if level_sum not in sum_level:
                    sum_level[level_sum] = level
                if level_sum > max_level_sum:
                    max_level_sum = level_sum
                    res = level
                level += 1
                level_sum = 0
                rightest_node = queue[-1] if queue else None
        return res

你可能感兴趣的:(OJ题目记录,leetcode,算法,java)