标签:turn maxsize 算法思路 tree elf pop node else level
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 import sys 9 class Solution: 10 # 返回二维列表[[1,2],[4,5]] 11 def __init__(self): 12 self.list = [] 13 self.result = [] 14 15 def levelOrder(self,level): 16 count = len(level) 17 while count > 0: 18 root = level.pop(0) 19 self.list.append(root.val) 20 if root.left != None: 21 level.append(root.left) 22 if root.right != None: 23 level.append(root.right) 24 count -= 1 25 if len(self.list) > 0: 26 self.result.append(self.list[:]) 27 self.list = [] 28 if len(level) > 0: 29 self.levelOrder(level) 30 31 # write code here 32 def maxLevelSum(self, root: TreeNode) -> int: 33 if root == None: 34 return self.list 35 else: 36 level = [] 37 level.append(root) 38 self.levelOrder(level) 39 maxval = -sys.maxsize 40 maxlevel = -1 41 for i in range(len(self.result)): 42 curlevelsum = sum(self.result[i]) 43 if curlevelsum > maxval: 44 maxval = curlevelsum 45 maxlevel = i + 1 46 return maxlevel 47
算法思路:二叉树层次遍历
标签:turn maxsize 算法思路 tree elf pop node else level
原文地址:https://www.cnblogs.com/asenyang/p/11371995.html