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
}

运行结果

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

相关推荐
我带你来这儿就是为了告诉你我2 分钟前
C++23新特性前瞻
开发语言·c++·算法
陌夏6 分钟前
快速排序 (Quick Sort)
算法
IronMurphy16 分钟前
【算法二十九】 437. 路径总和 III
算法·深度优先
2501_9083298517 分钟前
C++安全编程指南
开发语言·c++·算法
计算机安禾19 分钟前
【C语言程序设计】第39篇:预处理器与宏定义
c语言·开发语言·c++·vscode·算法·visual studio code·visual studio
参.商.22 分钟前
【Day43】49. 字母异位词分组
leetcode·golang
m0_5698814730 分钟前
C++中的装饰器模式变体
开发语言·c++·算法
吉哥机顶盒刷机31 分钟前
海信IP820N机顶盒的刷机教程
经验分享·刷机
笒鬼鬼32 分钟前
【API接口】最新可用红果短剧接口
算法·api·笒鬼鬼·红果短剧·接口源码
weixin_4219226933 分钟前
C++与边缘计算
开发语言·c++·算法