当前位置:网站首页>最大层内元素和
最大层内元素和
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
边栏推荐
- EFCore 反向工程
- [LeetCode Daily Question]——654. The largest binary tree
- How engineers treat open source
- [LeetCode Daily Question] - 103. Zigzag Level Order Traversal of Binary Tree
- nacos startup error, the database has been configured, stand-alone startup
- BioVendor Human Club Cellular Protein (CC16) Elisa Kit Research Fields
- Nanoprobes免疫测定丨FluoroNanogold试剂免疫染色方案
- Entry name 'org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt' collided
- AI目标分割能力,无需绿幕即可实现快速视频抠图
- [ORB_SLAM2] void Frame::ComputeImageBounds(const cv::Mat & imLeft)
猜你喜欢

一次SQL优化,数据库查询速度提升 60 倍

AI目标分割能力,无需绿幕即可实现快速视频抠图

Nanoprobes丨1-mercapto-(triethylene glycol) methyl ether functionalized gold nanoparticles

2022 Henan Youth Training League Game (3)

机器人领域期刊会议汇总

Nanoprobes多组氨酸 (His-) 标签标记:重组蛋白检测方案

记一次gorm事务及调试解决mysql死锁

GTK RGB图像绘制

Unable to log in to the Westward Journey

ros多客户端请求服务
随机推荐
永磁同步电机36问(三)——SVPWM代码实现
[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
考完PMP学什么?前方软考等着你~
How to adjust the cross cursor too small, CAD dream drawing calculation skills
Remember a pit for gorm initialization
"NetEase Internship" Weekly Diary (1)
2022-08-01 安装mysql监控工具phhMyAdmin
拼多多借力消博会推动国内农产品品牌升级 看齐国际精品农货
20. 用两个栈实现队列
Can Youxuan database import wrongly be restored?
2022-08-01 Install mysql monitoring tool phhMyAdmin
2022-08-01 Reflection
to-be-read list
2022-07-30 mysql8执行慢SQL-Q17分析
Outsourcing worked for three years, it was abolished...
2022年NPDP考完多久出成绩?怎么查询?
BioVendor人俱乐部细胞蛋白(CC16)Elisa试剂盒研究领域
Oracle数据类型介绍
[ORB_SLAM2] SetPose, UpdatePoseMatrices
NAS和私有云盘的区别?1篇文章说清楚