515. Find Largest Value in Each Tree Row(Medium)

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():
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution():
    def largestValues(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return None
#            return []
        list_a = [root]
        res = []
        while list_a:
            max_node = None
            list_b = []
            for n in list_a:
                max_node = max(n.val, max_node)
                if n.left:
                    list_b.append(n.left)
                if n.right:
                    list_b.append(n.right)
            res.append(max_node)
            list_a = list_b
        return res
原文地址:https://www.cnblogs.com/yancea/p/7521143.html