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

1.问题描述

在这里插入图片描述

2.解决办法

广度优先遍历:(经常使用)

  • 创建队列,队列是先进先出,并将根节点放入队列。
  • 判断根节点是否为空,为空直接返回res(ArrayList)
  • 还是以此放入队列 定义一个max同时赋值为Integer.MIN_VALUE,只要队列的数比他大就把值赋给max
  • 当一层遍历完,也就找到了第一层最大的数,放入res中
  • 接着再将max赋值为Integer.MIN_VALUE,再次遍历该层,后面以此类推。

3.代码实现

class Solution {
    public List<Integer> largestValues(TreeNode root) {
       Queue<TreeNode> queue = new LinkedList<>();
       	 queue.offer(root);
          ArrayList<Integer> res = new ArrayList<>();
          
          if(root==null) return res;
        
        while (!queue.isEmpty()) {
            int size = queue.size();
             int max = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (max<=poll.val ) {
                   max = poll.val;
                }
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
        
            res.add(max);
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值