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

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

示例:

输入: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

输出: [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 []

        result, queue, temp = [], [], []
        curr_right_node, next_right_node = root, root

        queue.append(root)

        while queue:
            curr_node = queue.pop(0)
            temp.append(curr_node.val)

            if curr_node.left:
                queue.append(curr_node.left)
                next_right_node = curr_node.left

            if curr_node.right:
                queue.append(curr_node.right)
                next_right_node = curr_node.right

            if curr_node == curr_right_node:
                result.append(max(temp))
                curr_right_node = next_right_node
                temp = []
        
        return result
posted @ 2018-09-21 12:51  yuyin  阅读(60)  评论(0编辑  收藏  举报