给定一棵二叉树的根节点 root
,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
# @lc app=leetcode.cn id=515 lang=python3
#
# [515] 在每个树行中找最大值
#
# @lc code=start
# 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 largestValues(self, root: Optional[TreeNode]) -> List[int]:
if not root: return [] #注意特殊情况:树为空返回[]
queue = [root]
list1 = []
while queue:
list2 = -2**31
for i in range(len(queue)):
a = queue.pop(0)#元素出队列
if a.left:
queue.append(a.left)
if a.right:
queue.append(a.right)
list2=max(list2,a.val)
list1.append(list2)
return list1
# @lc code=end