【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

解答

源代码

/**
 * 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);
        }
    }
}

总结

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

猜你喜欢

转载自blog.csdn.net/qq_57438473/article/details/132650401
今日推荐