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

总结

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

相关推荐
residual_fan2 分钟前
特征级SMOTE(Feature-level SMOTE)论文分享
人工智能·算法·数据挖掘·数据分析
xxwxx__4 分钟前
深入理解 C++ STL:stack、queue 与 deque 从使用到底层实现全解析
开发语言·c++·算法
sylviiiiiia15 分钟前
Leetcode hot100 多数元素/相交链表/反转链表
算法·leetcode·链表
CoderYanger18 分钟前
A.每日一题:3622. 判断整除性
java·程序人生·算法·leetcode·面试·职场和发展·蓝桥杯
rannn_11127 分钟前
【力扣hot100】动态规划专题|70、118、198、279、322、139、300、152、416、32
算法·leetcode·动态规划
渡之28 分钟前
ArduPilot(APM)滤波器之 HarmonicNotchFilter 深度解析
算法·无人机
我不会起名字32228 分钟前
一天一道算法题(26):栈的简单应用
java·数据结构·python·算法·leetcode·golang·
lvwangshu1 小时前
exBSGS 算法
数学·算法
不会就选b1 小时前
算法日常・每日刷题--<贪心+大根堆>2
数据结构·算法