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

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

java 复制代码
/**
 * 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头部
相关推荐
广州灵眸科技有限公司5 小时前
为RK3588注入澎湃算力:RK1820 AI加速卡完整适配与评测指南
linux·网络·人工智能·物联网·算法
qinian_ztc5 小时前
frida 14.2.18 安装报错解决
算法·leetcode·职场和发展
AI应用实战 | RE5 小时前
012、检索器(Retrievers)核心:从向量库中智能查找信息
人工智能·算法·机器学习·langchain
凤年徐5 小时前
C++手撕红黑树:从0到200行,拿下STL map底层核心
c++·后端·算法
Thomas.Sir5 小时前
AI 医疗之罕见病/疑难病辅助诊断系统从算法到实现【表型驱动与知识图谱推理】
人工智能·算法·ai·知识图谱
tankeven6 小时前
动态规划专题(03):区间动态规划从原理到实践(未完待续)
c++·算法·动态规划
田梓燊7 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
斯内科7 小时前
FFT快速傅里叶变换
算法·fft
2301_822703207 小时前
开源鸿蒙跨平台Flutter开发:幼儿疫苗全生命周期追踪系统:基于 Flutter 的免疫接种档案与状态机设计
算法·flutter·华为·开源·harmonyos·鸿蒙
贵慜_Derek7 小时前
Managed Agents 里,Harness 到底升级了什么?
人工智能·算法·架构