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
}
相关推荐
玛丽莲茼蒿3 小时前
Leetcode hot100 每日温度【中等】
算法·leetcode·职场和发展
样例过了就是过了4 小时前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
北顾笙9804 小时前
day38-数据结构力扣
数据结构·算法·leetcode
m0_629494734 小时前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai4 小时前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
水蓝烟雨6 小时前
3337. 字符串转换后的长度 II
算法·leetcode
_日拱一卒7 小时前
LeetCode:226翻转二叉树
数据结构·算法·leetcode
踩坑记录7 小时前
leetcode hot100 64. 最小路径和 medium 递归优化
leetcode·深度优先
lolo大魔王7 小时前
Go语言的并发、协调创建和通信机制
开发语言·golang
样例过了就是过了7 小时前
LeetCode热题100 最长有效括号
c++·算法·leetcode·动态规划