【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头部
相关推荐
CHANG_THE_WORLD2 小时前
金字塔降低采样
算法·金字塔采样
不知天地为何吴女士4 小时前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界4 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
励志要当大牛的小白菜6 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970446 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵7 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱喝矿泉水的猛男9 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao9 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
YouQian77210 小时前
Traffic Lights set的使用
算法
go546315846511 小时前
基于深度学习的食管癌右喉返神经旁淋巴结预测系统研究
图像处理·人工智能·深度学习·神经网络·算法