515. Find Largest Value in Each Tree Row 二叉树每一层的最大值

Posted Long Long Journey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了515. 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]

题意:找出二叉树一层的最大值

解法:用BFS的方式遍历每一层

  1. class Solution(object):
  2. def largestValues(self, root):
  3. """
  4. :type root: TreeNode
  5. :rtype: List[int]
  6. """
  7. result = []
  8. if not root:
  9. return result
  10. queue = [root]
  11. while queue:
  12. count = len(queue)
  13. res = -2147483648
  14. for i in range(count):
  15. curNode = queue.pop(0)
  16. res = max(curNode.val, res)
  17. if curNode.left:
  18. queue.append(curNode.left)
  19. if curNode.right:
  20. queue.append(curNode.right)
  21. result.append(res)
  22. return result







以上是关于515. Find Largest Value in Each Tree Row 二叉树每一层的最大值的主要内容,如果未能解决你的问题,请参考以下文章

515. Find Largest Value in Each Tree Row

515. Find Largest Value in Each Tree Row

leetcode--515. Find Largest Value in Each Tree Row

[LeetCode]515 Find Largest Value in Each Tree Row(dfs)

[leetcode-515-Find Largest Value in Each Tree Row]

(BFS 二叉树) leetcode 515. Find Largest Value in Each Tree Row