leetcode1161 Maximum Level Sum of a Binary Tree
1 """ 2 BFS遍历题,一遍AC 3 Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. 4 Return the smallest level X such that the sum of all the values of nodes at level X is maximal. 5 Example 1: 6 Input: [1,7,0,7,-8,null,null] 7 Output: 2 8 Explanation: 9 Level 1 sum = 1. 10 Level 2 sum = 7 + 0 = 7. 11 Level 3 sum = 7 + -8 = -1. 12 So we return the level with the maximum sum which is level 2. 13 """ 14 class TreeNode: 15 def __init__(self, x): 16 self.val = x 17 self.left = None 18 self.right = None 19 20 class Solution: 21 def maxLevelSum(self, root): 22 if root == None: 23 return 0 24 queue = [] 25 res = [] 26 queue.append(root) 27 while queue: 28 n = len(queue) 29 sum = 0 30 newqueue = [] 31 for _ in range(n): 32 x = queue.pop(0) 33 sum += x.val 34 if x.left != None: 35 newqueue.append(x.left) 36 if x.right != None: 37 newqueue.append(x.right) 38 queue = newqueue 39 res.append(sum) 40 return res.index(max(res))+1