python leetcode 515. Find Largest Value in Each Tree Row

You need to find the largest value in each row of a binary tree.


找出二叉树中每层的最大数。

513. Find Bottom Left Tree Value

637. Average of Levels in 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]
        """
        ans = []
        if not root:  
            return ans
        node = [root]
        while node:
            ans.append(max([i.val for i in node]))
            curr = []
            for each in node:
                if each.left:
                    curr.append(each.left)
                if each.right:
                    curr.append(each.right)
                node = curr
        return ans

猜你喜欢

转载自blog.csdn.net/DreamerLHQ/article/details/80198779