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

class Solution(object):
    def largestValues(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root is None:
            return []
        queue = [root]
        l = []
        while queue:
            size = len(queue)
            maxnum = float('-inf')
            for i in range(size):
                top = queue.pop(0)
                maxnum = max(maxnum, top.val)
                if top.left:
                    queue.append(top.left)
                if top.right:
                    queue.append(top.right)
            l.append(maxnum)
        return l
                
            

 

相关文章:

  • 2022-12-23
  • 2021-11-24
  • 2021-11-06
  • 2021-06-25
  • 2022-12-23
  • 2021-12-17
  • 2021-10-28
  • 2022-01-31
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2021-11-25
  • 2021-12-02
相关资源
相似解决方案