【LeetCode】515.在每个树行中找最大值

题目

给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。

示例1:

复制代码
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]

示例2:

复制代码
输入: root = [1,2,3]
输出: [1,3]

提示:

  • 二叉树的节点个数的范围是 [0,10^4]
  • -2^31 <= Node.val <= 2^31 - 1

解答

源代码

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        if (root == null) {
            return new ArrayList<Integer>();
        }

        List<Integer> res = new ArrayList<>();
        dfs(root, res, 0);

        return res;
    }

    public void dfs(TreeNode root, List<Integer> res, int curHeight) {
        if (curHeight == res.size()) {
            res.add(root.val);
        } else {
            res.set(curHeight, Math.max(res.get(curHeight), root.val));
        }

        if (root.left != null) {
            dfs(root.left, res, curHeight + 1);
        }

        if (root.right != null) {
            dfs(root.right, res, curHeight + 1);
        }
    }
}

总结

深度遍历二叉树并记录当前节点的层数,和列表中对应层数的值作对比,更新最大值。

相关推荐
scx2013100412 分钟前
20250814 最小生成树和重构树总结
c++·算法·最小生成树·重构树
阿巴~阿巴~21 分钟前
冒泡排序算法
c语言·开发语言·算法·排序算法
散11233 分钟前
01数据结构-交换排序
数据结构·算法
yzx9910131 小时前
Yolov模型的演变
人工智能·算法·yolo
weixin_307779132 小时前
VS Code配置MinGW64编译SQLite3库
开发语言·数据库·c++·vscode·算法
无聊的小坏坏2 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
wwww.bo2 小时前
机器学习(决策树)
算法·决策树·机器学习
辞--忧2 小时前
深入浅出决策树
算法·决策树·机器学习
Y200309162 小时前
决策树总结
算法·决策树·机器学习
lynn8570_blog2 小时前
低端设备加载webp ANR
前端·算法