515.find-largest-value-in-each-tree-row


515. 在每个树行中找最大值

您需要在二叉树的每一行中找到最大的值。

示例:

输入: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

输出: [1, 3, 9]

解法一

bfs

# 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: TreeNode) -> List[int]:

      if not root:
        return []

      result = []
      queue = [root]

      while queue:
        m = float('-inf')
        for i in range(len(queue)):
          node = queue.pop(0)
          m = max(node.val, m)
          if node.left:
            queue.append(node.left)
          if node.right:
            queue.append(node.right)
        result.append(m)

      return result