当前位置:网站首页>Leetcode daily question - 515 Find the maximum value in each tree row
Leetcode daily question - 515 Find the maximum value in each tree row
2022-06-28 20:36:00 【Did HYK write the algorithm today】
List of articles
subject
Given the root node of a binary tree root , Please find the maximum value of each layer in the binary tree .
Example
Example 1:
Input : root = [1,3,2,5,3,null,9]
Output : [1,3,9]
Example 2:
Input : root = [1,2,3]
Output : [1,3]
Tips :
The range of the number of nodes in a binary tree is [0,104]
-231 <= Node.val <= 231 - 1
Ideas
BFS, Simulating sequence traversal using queues , List the maximum value of each layer
Answer key
# 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]:
# Queue and result list
temp,res = deque(), []
if root is None:
return res
else:
temp.append(root)
while temp:
n, max_ = len(temp), -float('inf')
# Update the maximum value of each layer
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
边栏推荐
猜你喜欢

Racher add / delete node

如何使用 DataAnt 监控 Apache APISIX

Win 10 create a gin framework project

ThreadLocal原理

不同框架的绘制神经网络结构可视化

Figure neural network can also be used as CV backbone model. Huawei Noah Vig architecture is comparable to CNN and transformer

RT-Thread线程同步与线程通信

Visualization of neural network structure in different frames

2022 tea master (intermediate) examination simulated 100 questions and simulated examination

【学习笔记】主成分分析法介绍
随机推荐
Relevant calculation of sphere, etc
TcWind 模式設定
怎么理解云原生数据库的快速迭代?
2022 tea master (intermediate) examination simulated 100 questions and simulated examination
软件watchdog和ANR触发memory dump讲解
Globalsign's Pan domain SSL certificate
2. 整合 Filter
输入和输出实型数据
List of domestic database directory
【学习笔记】因子分析
LeetCode每日一题——522. 最长特殊序列 II
Pyinstaller打包pikepdf失败的问题排查
数据资产为王,如何解析企业数字化转型与数据资产管理的关系?
题解 Pie(POJ3122)超详细易懂的二分入门
Various types of long
员工薪资管理系统
不同框架的绘制神经网络结构可视化
题解 Ananagrams(UVa156)紫书P113map的应用
学习太极创客 — MQTT 第二章(七)ESP8266 MQTT 遗嘱应用
Input and output character data
