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
}

运行结果

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

相关推荐
CS创新实验室7 小时前
算法、齿轮与硅基大脑:数值计算发展简史
人工智能·算法·数值计算
海石8 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石8 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx8 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
imbackneverdie9 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃10 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录12 小时前
prompt-optimizer skill
算法
万法若空12 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
退休倒计时12 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
BomanGe112 小时前
NSK W1501FA高速精密滚珠丝杠技术手册
数据库·经验分享·规格说明书