【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头部
相关推荐
仟濹几秒前
算法打卡 day1 (2026-02-06 周四) | 算法: DFS | 1_卡码网98 可达路径 | 2_力扣797_所有可能的路径
算法·leetcode·深度优先
yang)1 分钟前
欠采样时的相位倒置问题
算法
历程里程碑5 分钟前
Linux20 : IO
linux·c语言·开发语言·数据结构·c++·算法
A尘埃7 分钟前
物流公司配送路径动态优化(Q-Learning算法)
算法
天若有情6738 分钟前
【自研实战】轻量级ASCII字符串加密算法:从设计到落地(防查岗神器版)
网络·c++·算法·安全·数据安全·加密
啊森要自信44 分钟前
CANN ops-cv:AI 硬件端视觉算法推理训练的算子性能调优与实战应用详解
人工智能·算法·cann
仟濹1 小时前
算法打卡day2 (2026-02-07 周五) | 算法: DFS | 3_卡码网99_计数孤岛_DFS
算法·深度优先
驭渊的小故事1 小时前
简单模板笔记
数据结构·笔记·算法
YuTaoShao1 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法一)前后缀分解
算法·leetcode·职场和发展
VT.馒头2 小时前
【力扣】2727. 判断对象是否为空
javascript·数据结构·算法·leetcode·职场和发展