Участник:Lenaermakova/ Maximum Level Sum of a Binary Tree

Материал из DISCOPAL
Перейти к: навигация, поиск

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

class Solution:
    def maxLevelSum(self, root: TreeNode) -> int:        
        current_level = [root]
        current_level_num = 1
        max_level_num = 1
        max_sum = float('-inf')
 
        while current_level:
            current_sum = 0
            next_level = []
 
            for node in current_level:
                current_sum += node.val
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
 
            if current_sum > max_sum:
                max_level_num = current_level_num
                max_sum = current_sum
 
            current_level = next_level
            current_level_num += 1
 
        return max_level_num