当前位置:网站首页>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
边栏推荐
- 怎么理解云原生数据库的易用性?
- Compression and decompression commands
- Past blue bridge cup test questions ants catch cold
- 2. integrate filter
- 数据标准化处理
- 2022茶艺师(中级)考试模拟100题及模拟考试
- mysql-发生系统错误1067
- csdn涨薪技术-Selenium自动化测试全栈总结
- A few lines of code can realize complex excel import and export. This tool class is really powerful!
- Day88. qiniu cloud: upload house source pictures and user avatars
猜你喜欢

Day88. qiniu cloud: upload house source pictures and user avatars

Visualization of neural network structure in different frames

2022 t elevator repair test question bank simulation test platform operation

Learning Tai Chi Maker - mqtt Chapter II (VII) esp8266 mqtt Testament application

数据资产为王,如何解析企业数字化转型与数据资产管理的关系?

API 网关 Apache APISIX 助力雪球双活架构演进

APISIX 助力中东社交软件,实现本地化部署

Lucene构建索引的原理及源代码分析

CNN-LSTM的flatten

不同框架的绘制神经网络结构可视化
随机推荐
学习太极创客 — MQTT 第二章(八)ESP8266 MQTT 用户密码认证
2022茶艺师(中级)考试模拟100题及模拟考试
Windows 64 bit download install my SQL
2022年P气瓶充装考试练习题及在线模拟考试
软件watchdog和ANR触发memory dump讲解
How to recover after Oracle delete accidentally deletes table data
ANR分析--问题1
ComparisonChain-文件名排序
Day88. qiniu cloud: upload house source pictures and user avatars
Database learning notes (sql04)
bluecmsv1.6代码审计
iterator中的next()为什么要强转?
T-test (test whether the mean difference between the two populations is significant)
Use of WC command
Relevant calculation of sphere, etc
522. longest special sequence II (greedy & double pointer)
Jenkins pipeline's handling of job parameters
各种类型长
Employee salary management system
2022焊工(初级)特种作业证考试题库及答案
