求二叉树按层求节点之和,返回加和最大的一层的层号,BFS
1 #1161
2 #Runtime: 273 ms (Beats 91.7%)
3 #Memory: 21.5 MB (Beats 67.26%)
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def maxLevelSum(self, root):
13 """
14 :type root: TreeNode
15 :rtype: int
16 """
17 ans = []
18 q = deque([root])
19 while q:
20 sz = len(q)
21 tp = 0
22 while sz:
23 sz -= 1
24 node = q.popleft()
25 tp += node.val
26 if node.left:
27 q.append(node.left)
28 if node.right:
29 q.append(node.right)
30 ans.append(tp)
31 return max(range(len(ans)), key=ans.__getitem__) + 1