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

https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/

解法一:层序

记录每层最大值

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import queue
class Solution:
    def largestValues(self, root: TreeNode) -> List[int]:
        res = []
        if not root:
            return res
        q = queue.Queue()
        q.put(root)
        while not q.empty():
            count = q.qsize()
            maxVal = -sys.maxsize
            for _ in range(count):
                node = q.get()
                maxVal = max(maxVal, node.val)    #更新最大值
                if node.left:
                    q.put(node.left)
                if node.right:
                    q.put(node.right)
            res.append(maxVal)
        return res

最后更新于