'''
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
这道题描述的是:
给我们一颗二叉树的根节点,返回每一层最大值的数组
思想:
广度优先遍历,把每一层最大值放入结果列表
python实现:
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
levels = [[root]]
values = [[root.val]]
for level in levels:
next_level = []
value = []
for node in level:
if node.left is not None:
next_level.append(node.left)
value.append(node.left.val)
if node.right is not None:
next_level.append(node.right)
value.append(node.right.val)
if next_level:
levels.append(next_level)
values.append(value)
res = []
for v in values:
res.append(max(v))
return res
精简一下代码:
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
values = []
level = [root]
while any(level):
values.append( max( [i.val for i in level] ) )
level = [child for node in level for child in [node.left, node.right ] if child is not None]
return values