【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头部
相关推荐
myw0712052 分钟前
Leetcode94.二叉数的中序遍历练习
c语言·数据结构·笔记·算法
songx_998 分钟前
leetcode(填充每个节点的下一个右侧节点指针 II)
java·数据结构·算法·leetcode
chenyuhao20249 分钟前
vector深度求索(上)实用篇
开发语言·数据结构·c++·后端·算法·类和对象
minstbe1 小时前
半导体数据分析:GPR算法小白入门(三) 晶体管I-V特性仿真教程
算法
未知陨落2 小时前
LeetCode:60.单词搜索
算法·leetcode
mmz12072 小时前
动态规划 练习(c++)
c++·算法·动态规划
tqs_123453 小时前
分sheet写入excel
开发语言·python·算法
西望云天3 小时前
基础组合计数(三道例题)
数据结构·算法·icpc
小灰灰的FPGA4 小时前
29.9元汉堡项目:基于matlab+FPGA的FFT寻峰算法实现
算法·matlab·fpga开发
成成成成成成果4 小时前
软件测试面试八股文:测试技术 10 大核心考点(二)
python·功能测试·测试工具·面试·职场和发展·安全性测试