当前位置:网站首页>LeetCode每日一题——515. 在每个树行中找最大值
LeetCode每日一题——515. 在每个树行中找最大值
2022-06-28 20:25:00 【hyk今天写算法了吗】
题目
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
提示:
二叉树的节点个数的范围是 [0,104]
-231 <= Node.val <= 231 - 1
思路
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
from collections import deque
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
# 队列和结果列表
temp,res = deque(), []
if root is None:
return res
else:
temp.append(root)
while temp:
n, max_ = len(temp), -float('inf')
# 更新每层最大值
for i in range(n):
index = temp.popleft()
max_ = max(max_, index.val)
if index.left is not None:
temp.append(index.left)
if index.right is not None:
temp.append(index.right)
res.append(max_)
return res
边栏推荐
- Grep text search tool
- 软件watchdog和ANR触发memory dump讲解
- 【学习笔记】因子分析
- 核芯物联蓝牙aoa定位系统服务器配置估算
- 1. 整合 Servlet
- How to recover after Oracle delete accidentally deletes table data
- odoo15 Module operations are not possible at this time, please try again later or contact your syste
- 各种类型长
- 圆球等的相关计算
- odoo15 Module operations are not possible at this time, please try again later or contact your syste
猜你喜欢

Shell reads the value of the JSON file

Lecture 30 linear algebra Lecture 4 linear equations
![[go language questions] go from 0 to entry 5: comprehensive review of map, conditional sentences and circular sentences](/img/7a/16b481753d7d57f50dc8787eec8a1a.png)
[go language questions] go from 0 to entry 5: comprehensive review of map, conditional sentences and circular sentences

bluecmsv1.6代码审计

RT thread thread synchronization and thread communication

应用实践 | 10 亿数据秒级关联,货拉拉基于 Apache Doris 的 OLAP 体系演进(附 PPT 下载)

csdn涨薪技术-Selenium自动化测试全栈总结

Data standardization processing

2022焊工(初级)特种作业证考试题库及答案

openGauss内核分析之查询重写
随机推荐
03.hello_ rust
Flatten of cnn-lstm
Characters and integers
How to analyze the relationship between enterprise digital transformation and data asset management?
Employee salary management system
ref属性,props配置,mixin混入,插件,scoped样式
Can layoffs really save China's Internet?
社招两年半10个公司28轮面试面经
2022 P cylinder filling test exercises and online simulation test
ThreadLocal原理
ComparisonChain-文件名排序
2022焊工(初级)特种作业证考试题库及答案
Jenkins pipeline's handling of job parameters
two thousand three hundred and forty-two
odoo15 Module operations are not possible at this time, please try again later or contact your syste
A few lines of code can realize complex excel import and export. This tool class is really powerful!
Leetcode week 299
Past blue bridge cup test questions ants catch cold
大智慧上怎么进行开户啊, 安全吗
软件watchdog和ANR触发memory dump讲解
