当前位置:网站首页>最大层内元素和
最大层内元素和
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
边栏推荐
- 罗德里格斯公式(Rodrigues‘ Rotation Formula)推导
- 使用self和_(下划线)的区别
- Software testing Interface automation testing Pytest framework encapsulates requests library Encapsulates unified request and multiple base path processing Interface association encapsulation Test cas
- Centos7 安装postgresql并开启远程访问
- 使用docker安装mysql
- Use DBeaver for mysql data backup and recovery
- 面对职场“毕业”,PM&PMO应该如何从容的应对?如何跳槽能够大幅度升职加薪?
- 欧拉公式的证明
- 十字光标太小怎么调节、CAD梦想画图算量技巧
- Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
猜你喜欢
【LeetCode每日一题】——103.二叉树的锯齿形层序遍历
Use DBeaver for mysql data backup and recovery
nacos startup error, the database has been configured, stand-alone startup
GTK RGB图像绘制
BI-SQL丨WHILE
BioVendor Human Club Cellular Protein (CC16) Elisa Kit Research Fields
ApiFox 基本使用教程(浅尝辄止,非广)
永磁同步电机36问(二)——机械量与电物理量如何转化?
Golang分布式应用之定时任务
Handwritten Blog Platform ~ Day Two
随机推荐
Entry name 'org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt' collided
字典常用方法
Check if IP or port is blocked
使用self和_(下划线)的区别
使用docker安装mysql
The underlying data structure of Redis
PHP uses PHPRedis and Predis
"NetEase Internship" Weekly Diary (1)
2022年NPDP考完多久出成绩?怎么查询?
CodeTon Round 2 D. Magical Array
CASE2023
Software testing Interface automation testing Pytest framework encapsulates requests library Encapsulates unified request and multiple base path processing Interface association encapsulation Test cas
NAS和私有云盘的区别?1篇文章说清楚
[ORB_SLAM2] SetPose, UpdatePoseMatrices
messy website
Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
Simple example of libcurl accessing url saved as file
PAT甲级打卡-1001-1004
Chopper webshell feature analysis
Service discovery of kubernetes