力扣hot100 - 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();
        Queue<TreeNode> q = new LinkedList();
        if(root == null) return res;
        q.add(root);

        while(!q.isEmpty()){
            int l = q.size();
            while(l > 0){
            TreeNode cur = q.peek();
            q.poll();
            if(l == 1){
                res.add(cur.val);
            }
            l--;
            if(cur.left != null){
                q.add(cur.left);
            }
            if(cur.right != null){
                q.add(cur.right);
            }
            }
        }
        return res;
    }
}
相关推荐
goodluckyaa8 小时前
thread block grid模型
算法
武帝为此8 小时前
【Rabbit加密算法介绍】
算法·安全
m0_716765238 小时前
数据结构三要素、时间复杂度计算详解
开发语言·数据结构·c++·经验分享·笔记·算法·visual studio
网安INF8 小时前
数据结构第二章复习:线性表
java·开发语言·数据结构
米粒18 小时前
力扣算法刷题 Day 36
算法·leetcode·职场和发展
北顾笙9808 小时前
day21-数据结构力扣
数据结构
And_Ii8 小时前
3740. 三个相等元素之间的最小距离 I
c++·算法
csuzhucong8 小时前
puzzle(0334)双面数局
数据结构·算法
强盛机器学习~8 小时前
2026年SCI一区新算法-贝塞尔曲线优化算法(BCO)-公式原理详解与性能测评 Matlab代码免费获取
算法·matlab·进化计算·智能优化算法·元启发式算法·群体智能算法
翟天保Steven8 小时前
空间载波移相干涉算法(SPSI)
算法·激光干涉·精密量测