0
点赞
收藏
分享

微信扫一扫

LeetCode 515. 在每个树行中找最大值

萧让听雪 2022-01-09 阅读 95

层序遍历的应用:
移步-LeetCode 515. 在每个树行中找最大值
移步->LeetCode 104. 二叉树的最大深度
移步->LeetCode 102. 二叉树的层序遍历
移步->LeetCode 226. 翻转二叉树

题目链接 515. 在每个树行中找最大值

思路:
采用层序遍历,每层计算得到最大值,然后每层遍历完后加入到结果列表中。注意,初始最大值设置为-(1 << 31)。
在这里插入图片描述

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> reslist = new ArrayList<Integer>();
        if(root == null) return reslist;
        Queue<TreeNode> que = new LinkedList<TreeNode>();
        que.offer(root);
        while(!que.isEmpty()){
            int len = que.size();
            int max = -(1 << 31);
            while(len>0){
                TreeNode curNode = que.poll();
                max = curNode.val>max?curNode.val:max;
                if(curNode.left!=null) que.offer(curNode.left);
                if(curNode.right!=null) que.offer(curNode.right);
                len--;
            }
            reslist.add(max);
        }
        return reslist;
    }
}
举报

相关推荐

0 条评论