leetcode算法: Find Largest Value in Each Tree Row
Posted 稀里糊涂林老冷
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode算法: Find Largest Value in Each Tree Row相关的知识,希望对你有一定的参考价值。
‘‘‘
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实现:
1 class Solution(object):
2 def largestValues(self, root):
3 """
4 :type root: TreeNode
5 :rtype: List[int]
6 """
7 if not root:
8 return []
9 levels = [[root]]
10 values = [[root.val]]
11 for level in levels:
12 next_level = []
13 value = []
14 for node in level:
15 if node.left is not None:
16 next_level.append(node.left)
17 value.append(node.left.val)
18 if node.right is not None:
19 next_level.append(node.right)
20 value.append(node.right.val)
21 if next_level:
22 levels.append(next_level)
23 values.append(value)
24 res = []
25 for v in values:
26 res.append(max(v))
27 return res
精简一下代码:
1 class Solution(object):
2 def largestValues(self, root):
3 """
4 :type root: TreeNode
5 :rtype: List[int]
6 """
7 values = []
8 level = [root]
9 while any(level):
10 values.append( max( [i.val for i in level] ) )
11 level = [child for node in level for child in [node.left, node.right ] if child is not None]
12 return values
以上是关于leetcode算法: Find Largest Value in Each Tree Row的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Find Largest Value in Each Tree Row
[LeetCode] 515. Find Largest Value in Each Tree Row
[LeetCode]515 Find Largest Value in Each Tree Row(dfs)
LeetCode: Find Largest Value in Each Tree Row