Golang | Leetcode Golang题解之第515题在每个树行中找最大值

题目:

题解:

Go 复制代码
func largestValues(root *TreeNode) (ans []int) {
    if root == nil {
        return
    }
    q := []*TreeNode{root}
    for len(q) > 0 {
        maxVal := math.MinInt32
        tmp := q
        q = nil
        for _, node := range tmp {
            maxVal = max(maxVal, node.Val)
            if node.Left != nil {
                q = append(q, node.Left)
            }
            if node.Right != nil {
                q = append(q, node.Right)
            }
        }
        ans = append(ans, maxVal)
    }
    return
}

func max(a, b int) int {
    if b > a {
        return b
    }
    return a
}
相关推荐
洛水水21 小时前
【力扣100题】30.二叉树的直径
算法·leetcode·职场和发展
洛水水1 天前
【力扣100题】32.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
如竟没有火炬1 天前
用队列实现栈
开发语言·数据结构·python·算法·leetcode·深度优先
水木流年追梦1 天前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式
洛水水1 天前
【力扣100题】31.二叉树的层序遍历
算法·leetcode·职场和发展
洛水水1 天前
【力扣100题】41.爬楼梯
算法·leetcode·职场和发展
Pkmer1 天前
LeetCode 上极少见的工程级滑窗实现
python·leetcode
sheeta19981 天前
LeetCode 每日一题笔记 日期:2026.05.13 题目:1674. 使数组互补的最少操作次数
笔记·算法·leetcode
YL200404261 天前
038翻转二叉树
数据结构·leetcode
Liangwei Lin1 天前
LeetCode 287. 寻找重复数
算法·leetcode·职场和发展