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

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

示例:

输入: 

          1
         / \
        3   2
       / \   \  
      5   3   9 

输出: [1, 3, 9]

思路:按行搜索,也就是按层次进行搜索,使用BFS。

# 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 not root:
            return []

        res = []
        nodeList = [root]

        while nodeList:
            nodeTemp = []
            nodeNext = []
            
            for i in nodeList:
                nodeTemp.append(i.val)
                
                if i.left:
                    nodeNext.append(i.left)
                if i.right:
                    nodeNext.append(i.right)
                
            res.append(max(nodeTemp))
            nodeList = nodeNext
        
        return res
                

猜你喜欢

转载自blog.csdn.net/qq_41805514/article/details/82947339
今日推荐