题目
给定一棵二叉树的根节点 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