LeetCode | 0515. 在每个树行中找最大值【Python】

本文介绍了如何使用广度优先搜索(BFS)策略来解决力扣上的一个问题,即在给定的二叉树中找到每一行的最大值。通过创建一个双端队列并逐层遍历树,可以有效地找到每一层的最大值。提供的Python代码实现详细展示了这一过程。
摘要由CSDN通过智能技术生成

Problem

LeetCode

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

Example 1:

img

Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]

Example 2:

Input: root = [1,2,3]
Output: [1,3]

Example 3:

Input: root = [1]
Output: [1]

Example 4:

Input: root = [1,null,2]
Output: [1,2]

Example 5:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree will be in the range [0, 104].
  • -231 <= Node.val <= 231 - 1

问题

力扣

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

示例:

输入: 
	  1
     / \
    3   2
   / \   \  
  5   3   9 
输出: [1, 3, 9]

思路

BFS

使用 BFS 遍历完每一层,将该层最大值加入 res 中。

Python3 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def largestValues(self, root: TreeNode) -> List[int]:
        import collections
        if not root:
            return []
        res = []
        q = collections.deque()
        q.append(root)
        while q:
            size = len(q)
            tmp_max = -float('inf')
            # 取每一层最大值
            for i in range(size):
                node = q.popleft()
                tmp_max = max(tmp_max, node.val)
                # 一层树遍历完,加入该层最大值
                if i == size - 1:
                    res.append(tmp_max)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
        return res

GitHub 链接

Python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wonz

创作不易,一块就行。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值