zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    多线程
    Java I/O简述
    Java集合
    Java常用类
    Java面向对象基础知识汇总
    Java标识符和关键字
    认识Java
    mvn打包源码和生成javadoc
    Http协议概述
    exe可执行程序及堆栈分配(转载)
  • 原文地址:https://www.cnblogs.com/yawenw/p/12291170.html
Copyright © 2011-2022 走看看