leetcode-515:在每个树行中找最大值
题目
题目链接
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
解释:
1
/ \
3 2
/ \ \
5 3 9
示例2:
输入: root = [1,2,3]
输出: [1,3]
解释:
1
/ \
2 3
示例3:
输入: root = [1]
输出: [1]
示例4:
输入: root = [1,null,2]
输出: [1,2]
解释:
1
\
2
示例5:
输入: root = []
输出: []
解题
方法一: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
class Solution:
def largestValues(self, root: TreeNode) -> List[int]:
if not root:
return []
res = []
queue = [root]
while queue:
l = len(queue)
tmp = []
for _ in range(l):
cur = queue.pop(0)
tmp.append(cur.val)
left,right = cur.left,cur.right
if left:
queue.append(left)
if right:
queue.append(right)
res.append(max(tmp)) ## 修改的地方
return res