【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);
        }
    }
}

总结

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

相关推荐
金融小师妹1 分钟前
解码美元-黄金负相关:LSTM-Attention因果发现与黄金反弹推演
大数据·人工智能·算法
1nv1s1ble13 分钟前
记录rust滥用lazy_static导致的一个bug
算法·rust·bug
青山是哪个青山28 分钟前
动态规划DP
算法·动态规划
looklight1 小时前
7. 整数反转
c++·算法·leetcode·职场和发展
Closet1231 小时前
Codeforces 2025/6/11 日志
c++·算法·codeforces
天真小巫2 小时前
2025.6.11总结
职场和发展
緈福的街口2 小时前
【leetcode】36. 有效的数独
linux·算法·leetcode
励碼5 小时前
美团完整面经
java·面试·职场和发展·sass·美团
心扬5 小时前
python数据结构和算法(5)
数据结构·python·算法