# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution(object): defmaxLevelSum(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return0
# 求各分層數值模板 deftrv(root): if root == None: return self.lvl += 1 if self.lvl > len(self.arr): self.arr.append([root.val]) else: self.arr[self.lvl-1].append(root.val) trv(root.left) trv(root.right) self.lvl -= 1 self.lvl = 0 self.arr = [] trv(root) # 若有最大和相等,求其最小層 arr = [sum(c) for c in self.arr]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution(object): defmaxLevelSum(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return0
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution(object): defmaxLevelSum(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return0
q = deque() q.append(root) arr = []
while q: l = len(q) cnt = 0 flg = 0 for i inrange(l): cur = q.popleft() if cur != None: flg = 1 cnt += cur.val q.append(cur.left) q.append(cur.right) if flg == 1: arr.append(cnt)