当前位置:网站首页>最大层内元素和
最大层内元素和
2022-08-02 02:26:00 【小小草帽】
题目
给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。
请返回层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个。
示例
示例 1:
输入:root = [1,7,0,7,-8,null,null]
输出:2
解释:
第 1 层各元素之和为 1,
第 2 层各元素之和为 7 + 0 = 7,
第 3 层各元素之和为 7 + -8 = -1,
所以我们返回第 2 层的层号,它的层内元素之和最大。
示例 2:
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127]
输出:2
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-level-sum-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法:
BFS:利用广度优先遍历逐层计算每一层的和,然后返回和最大的层的编号。
DFS:创建数组存储每一层的和,利用深度优先遍历计算每层和。
代码
BFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
queue =[root]
res = float("-inf")
number = 0
piece = 0
while queue:
n = len(queue)
ans = 0
number += 1
for _ in range(n):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
ans += node.val
if ans > res:
piece = number
res = ans
return piece
DFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
sum = []
def dfs(node, level):
if level == len(sum):
sum.append(node.val)
else:
sum[level] += node.val
if node.left:
dfs(node.left, level + 1)
if node.right:
dfs(node.right, level + 1)
dfs(root, 0)
return sum.index(max(sum)) + 1
边栏推荐
- 2022河南青训联赛第(三)场
- 灰度传感器、、、diy原理。。图
- 一次SQL优化,数据库查询速度提升 60 倍
- C#测试项目中属性的用法
- nacos startup error, the database has been configured, stand-alone startup
- swift project, sqlcipher3 -> 4, cannot open legacy database is there a way to fix it
- 2022-07-30 mysql8 executes slow SQL-Q17 analysis
- 51. 数字排列
- 个人博客系统项目测试
- The first time I wrote a programming interview question for Niu Ke: input a string and return the letter with the most occurrences of the string
猜你喜欢
随机推荐
oracle query scan full table and walk index
2022-08-01 Install mysql monitoring tool phhMyAdmin
The state status is displayed incorrectly after the openGauss switch
BI - SQL 丨 WHILE
1688API
CodeTon Round 2 D. Magical Array
项目场景 with ERRTYPE = cudaError CUDA failure 999 unknown error
2022-07-30 mysql8 executes slow SQL-Q17 analysis
AI目标分割能力,无需绿幕即可实现快速视频抠图
nacos启动报错,已配置数据库,单机启动
isa指针使用详情
Safety (1)
Handwritten Blog Platform ~ Day Two
Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
Personal blog system project test
机器人领域期刊会议汇总
使用DBeaver进行mysql数据备份与恢复
canal同步Mariadb到Mysql
Entry name 'org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt' collided
Nanoprobes多组氨酸 (His-) 标签标记:重组蛋白检测方案









