当前位置: 首页 > news >正文

【leetcode hot 100 199】二叉树的右视图

解法一:层级遍历,右侧看到的节点就是每一层最后一个元素

/**
 * 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> rightSideView(TreeNode root) {
        // 层级遍历,右侧看到的节点就是每一层最后一个元素
        List<Integer> res = new ArrayList<>();
        if(root==null){
            return res;
        }
        // 层级遍历
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root); // 是offer不是poll
        while(!queue.isEmpty()){
            int qSize = queue.size();
            TreeNode node = null;
            for(int i=0;i<qSize;i++){
                node = queue.poll();
                if(node.left!=null){
                    queue.offer(node.left);
                }
                if(node.right!=null){
                    queue.offer(node.right);
                }
            }
            res.add(node.val);
        }
        return res;
    }
}

注意:

  • 最开始只需要把root放入queue中,不需要poll:queue.offer(root)
  • pq.offer(pq_):将pq_元素加入优先队列pq中;pq.peek():取出队列pq头部;pq.poll():删除队列pq头部

相关文章:

  • ModelScope推理QwQ32B
  • SpringBoot手动注册定时任务
  • 【WRF-Urban】使用 CGLC-MODIS-LCZ_100m 数据集运行 WRF 时的城市参数化问题
  • 从0开始搭建微服务架构特别篇SpringCloud网关聚合knife4j
  • S/4 ERP QM 结合 EWM
  • 【C#】Http请求设置接收不安全的证书
  • 通义Qwen实战(1): 环境安装及微调实战
  • 蓝桥杯每日一题——Acwing 5438. 密接牛追踪2
  • Linux mount和SSD分区
  • JetsonOrin源码安装部署PaddlePaddle
  • 【java】集合的基本使用
  • [Linux][经验总结]Ubuntu6.11.0 docker更换镜像源(实操可用的正确方法)
  • 深入解析前后端分离架构:原理、实践与最佳方案
  • 算法手记5
  • ngx_event_conf_t
  • Qt事件处理(重写event)
  • nginx不在默认的yum仓库的解决方法
  • libstdc++ GLIBCXX_3.4.20 not found 解决方法
  • 计算机毕业设计:基于SSM理发店造型中心网上预约评价系统
  • C11标准对于C语言的内存模型的描述
  • 余姚有专业做网站的吗/站长素材网
  • 2021年中国企业500强/苏州搜索引擎排名优化商家
  • wordpress指定页面提示框/长沙网站优化
  • 提供微商城网站建设/百度推广管理系统
  • 上海建筑网站/广州seo全网营销
  • 做设计找图有哪些网站/电商运营方案计划书