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
}

运行结果

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

相关推荐
JieE21236 分钟前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack208 小时前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树10 小时前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2121 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2121 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术1 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦1 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050731 天前
(一)小红的数组操作
算法·编程语言
怕浪猫2 天前
Electron 系列文章封面图
算法·架构·前端框架