• 剑指 Offer II 044. 二叉树每层的最大值


    题目链接

    力扣

    题目描述

    给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。

    示例1:

    输入: root = [1,3,2,5,3,null,9]
    输出: [1,3,9]
    解释:
              1
             / \
            3   2
           / \   \  
          5   3   9 
    示例2:

    输入: root = [1,2,3]
    输出: [1,3]
    解释:
              1
             / \
            2   3
    示例3:

    输入: root = [1]
    输出: [1]
    示例4:

    输入: root = [1,null,2]
    输出: [1,2]
    解释:      
               1 
                \
                 2     
    示例5:

    输入: root = []
    输出: []
     

    提示:

    二叉树的节点个数的范围是 [0,104]
    -231 <= Node.val <= 231 - 1

    解题思路

    dfs:存储一个当前高度值,在遍历到每个元素时与答案数组中的当前高度进行比较

    bfs:维护一个结点数组,每一层遍历完后进行清空

    Python使用了dfs,Go用了bfs

    代码

    Python

    1. class Solution:
    2. def largestValues(self, root: TreeNode) -> list[int]:
    3. ans = []
    4. def dfs(node: TreeNode, curHeight: int) -> None:
    5. if not node:
    6. return
    7. if curHeight == len(ans):
    8. ans.append(node.val)
    9. else:
    10. ans[curHeight] = max(ans[curHeight], node.val)
    11. dfs(node.left, curHeight + 1)
    12. dfs(node.right, curHeight + 1)
    13. dfs(root, 0)
    14. return ans

    Go

    1. func largestValues(root *TreeNode) []int {
    2. if root == nil {
    3. return nil
    4. }
    5. ans := []int{}
    6. queue := []*TreeNode{root}
    7. for len(queue) > 0 {
    8. curMax := math.MinInt32
    9. tmp := queue
    10. queue = nil
    11. for _, node := range tmp {
    12. if node.Val > curMax {
    13. curMax = node.Val
    14. }
    15. if node.Left != nil {
    16. queue = append(queue, node.Left)
    17. }
    18. if node.Right != nil {
    19. queue = append(queue, node.Right)
    20. }
    21. }
    22. ans = append(ans, curMax)
    23. }
    24. return ans
    25. }

  • 相关阅读:
    【pod进阶】
    如何编写规范的交互文档
    vMAP——论文解析
    淘宝扭蛋机小程序:现在是否是最佳开发时机?
    《opencv学习笔记》-- Shi-Tomasi 角点检测
    pgsql查询近一日,近一月,近一年的数据
    选择护眼台灯的标准,教大家如何挑选护眼灯
    成都Java开发已经饱和了?
    Spring Boot与Web组件,值得学习(附加记住idea快捷键)
    Compose 动画艺术探索之动画规格
  • 原文地址:https://blog.csdn.net/qq_33523932/article/details/125545925