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
}
相关推荐
hn小菜鸡7 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
亮亮爱刷题10 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
大模型铲屎官10 天前
【Go语言-Day 7】循环控制全解析:从 for 基础到 for-range 遍历与高级控制
开发语言·人工智能·后端·golang·大模型·go语言·循环控制
zmuy10 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
chao_78910 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king10 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法
呆呆的小鳄鱼10 天前
leetcode:746. 使用最小花费爬楼梯
算法·leetcode·职场和发展
YuTaoShao10 天前
【LeetCode 热题 100】42. 接雨水——(解法一)前后缀分解
java·算法·leetcode·职场和发展
mxpan10 天前
深入探究 Go 语言中使用 SQLite 数据库
数据库·golang·sqlite
YuforiaCode10 天前
(LeetCode 面试经典 150 题) 27.移除元素
算法·leetcode·面试