Leetcode—1161. 最大层内元素和【中等】

2025每日刷题(233)

Leetcode---1161. 最大层内元素和

BFS实现代码

go 复制代码
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxLevelSum(root *TreeNode) int {
    queue := []*TreeNode{root}
    i := 0
    ans := 0
    line := 0
    mx := -0x3f3f3f3f
    for(len(queue) > 0) {
        i++
        ans = 0
        for sz := len(queue); sz > 0; sz-- {
            root = queue[0]
            queue = queue[1:]
            ans += root.Val
            if(root.Left != nil) {
                queue = append(queue, root.Left)
            }
            if(root.Right != nil) {
                queue = append(queue, root.Right)
            }
        }
        if(mx < ans) {
            mx = ans
            line = i
        }
    }
    return line
}

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
CodeByV1 天前
【算法题】模拟
算法
qq_337599461 天前
shell 脚本相关
经验分享
s09071361 天前
FPGA加速:Harris角点检测全解析
图像处理·算法·fpga开发·角点检测
前端程序猿之路1 天前
30天大模型学习之Day 2:Prompt 工程基础系统
大数据·人工智能·学习·算法·语言模型·prompt·ai编程
星火开发设计1 天前
堆排序原理与C++实现详解
java·数据结构·c++·学习·算法·排序算法
2501_941803621 天前
在柏林智能城市照明场景中构建实时调控与高并发能耗数据分析平台的工程设计实践经验分享
算法
福楠1 天前
C++ STL | list
c语言·开发语言·数据结构·c++·算法·list
努力学算法的蒟蒻1 天前
day55(1.6)——leetcode面试经典150
算法·leetcode·面试
s砚山s1 天前
代码随想录刷题——二叉树篇(十)
算法