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

总结

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

相关推荐
蒟蒻小袁21 分钟前
力扣面试150题--全排列
算法·leetcode·面试
mit6.82437 分钟前
[Backlog] 核心协调器 | 终端用户界面(TUI)实现 | 多分支任务冲突解决 | 测试验证体系
人工智能·算法
SKYDROID云卓小助手1 小时前
无人设备遥控器之无线电频率篇
服务器·网络·单片机·嵌入式硬件·算法
十八岁讨厌编程1 小时前
【算法训练营Day11】二叉树part1
算法
緈福的街口2 小时前
【leetcode】2236. 判断根节点是否等于子节点之和
算法·leetcode·职场和发展
祁思妙想2 小时前
【LeetCode100】--- 1.两数之和【复习回滚】
数据结构·算法·leetcode
薰衣草23332 小时前
一天两道力扣(2)
算法·leetcode
小鲈鱼-2 小时前
【LeetCode4.寻找两个正序数组的中位数】二分O(log(m+n))
c++·算法
橘颂TA2 小时前
【C++】红黑树的底层思想 and 大厂面试常问
数据结构·c++·算法·红黑树
chao_7892 小时前
二分查找篇——寻找旋转排序数组中的最小值【LeetCode】
python·线性代数·算法·leetcode·矩阵