当前位置:网站首页>最大层内元素和
最大层内元素和
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
边栏推荐
- Check if IP or port is blocked
- Software testing Interface automation testing Pytest framework encapsulates requests library Encapsulates unified request and multiple base path processing Interface association encapsulation Test cas
- 【web】Understanding Cookie and Session Mechanism
- [Server data recovery] Data recovery case of server Raid5 array mdisk disk offline
- oracle query scan full table and walk index
- 【 wheeled odometer 】
- Unable to log in to the Westward Journey
- PHP live source code to achieve simple barrage effect related code
- 20. 用两个栈实现队列
- CodeTon Round 2 D. Magical Array
猜你喜欢

GTK RGB图像绘制

ros多客户端请求服务

openGauss切换后state状态显示不对

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

Win Go development kit installation configuration, GoLand configuration

oracle query scan full table and walk index

ApiFox 基本使用教程(浅尝辄止,非广)

机器人领域期刊会议汇总

FOFAHUB使用测试

AI目标分割能力,无需绿幕即可实现快速视频抠图
随机推荐
Service discovery of kubernetes
MySQL - CRUD operations
菜刀webshell特征分析
53. 最小的k个数
mysql 查看死锁
【CNN记录】tensorflow slice和strided_slice
EFCore 反向工程
使用self和_(下划线)的区别
【Unity入门计划】2D Game Kit:初步了解2D游戏组成
nacos startup error, the database has been configured, stand-alone startup
NIO‘s Sword(牛客多校赛)
canal同步Mariadb到Mysql
bool框架::PosInGrid (const简历:关键点kp, int &posX, int诗句)
OC中成员变量,实例变量和属性之间的区别和联系
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
[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
灰度传感器、、、diy原理。。图
Rasa 3.x 学习系列- Rasa - Issues 4873 dispatcher.utter_message 学习笔记
Install mysql using docker
Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community