leetcode1161

Posted asenyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1161相关的知识,希望对你有一定的参考价值。

 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         

算法思路:二叉树层次遍历

以上是关于leetcode1161的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1161 最大层内元素和[BFS 二叉树] HERODING的LeetCode之路

题目1161:Repeater(规律输出图形)

POJ1161——The Suspects

XDOJ_1161_数学

洛谷P1161 开灯

每日一题1161. 最大层内元素和