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

 



posted @ 2017-11-27 19:00  稀里糊涂林老冷  阅读(236)  评论(0编辑  收藏  举报