0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点# LeetCode程序员面试金典:在每个树行中找最大值

题目

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


 


示例1:




输入: root = [1,3,2,5,3,null,9]

输出: [1,3,9]

示例2:


输入: root = [1,2,3]

输出: [1,3]

 

代码实现

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        if (root == null) {
            return new ArrayList<Integer>();
        }
        List<Integer> res = new ArrayList<Integer>();
        dfs(res, root, 0);
        return res;
    }

    public void dfs(List<Integer> res, TreeNode root, 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(res, root.left, curHeight + 1);
        }
        if (root.right != null) {
            dfs(res, root.right, curHeight + 1);
        }
    }
}


举报

相关推荐

0 条评论