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
}
相关推荐
jieyucx2 小时前
Go语言深度解剖:Map扩容机制全解析(增量扩容+等量扩容+渐进式迁移)
开发语言·后端·golang·map·扩容策略
刃神太酷啦3 小时前
扒透 STL 底层!map/set 如何封装红黑树?迭代器逻辑 + 键值限制全手撕----《Hello C++ Wrold!》(23)--(C/C++)
java·c语言·javascript·数据结构·c++·算法·leetcode
王码码20353 小时前
Go语言的内存管理:原理与实战
后端·golang·go·接口
_深海凉_5 小时前
LeetCode热题100-分割回文串
算法·leetcode·职场和发展
~|Bernard|7 小时前
一.go语言中slice底层原理(2026-5-7)
golang·go
流年如夢8 小时前
单链表Ⅲ(LeetCode)
数据结构·算法·leetcode·职场和发展
~|Bernard|10 小时前
二.go语言中map的底层原理(2026-5-8)
算法·golang·哈希算法
mask哥10 小时前
力扣算法java实现汇总整理(下)
java·算法·leetcode
平凡但不平庸的码农10 小时前
Go 错误处理详解
开发语言·后端·golang
样例过了就是过了10 小时前
LeetCode热题100 编辑距离
数据结构·c++·算法·leetcode·动态规划