515. 在每个树行中找最大值
Difficulty: 中等
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/
3 2
/
5 3 9
输出: [1, 3, 9]
Solution
Language: ****
BFS+queue实现层序遍历,十分easy,一次AC。
# 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 None
queue, res = [root], []
while queue:
curLevel, size = [], len(queue)
for i in range(size):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
curLevel.append(node.val)
res.append(max(curLevel))
return res