力扣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;
    }
}
相关推荐
小O的算法实验室7 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
小飞学编程...7 小时前
【哈希表】
数据结构·哈希算法·散列表
Tbisnic8 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx8 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归9 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing9 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习10 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨10 小时前
基础数论总结
笔记·学习·算法
动词ing11 小时前
【C语言】结构体+文件基础
c语言·开发语言·数据结构
夜不会漫长12 小时前
C++入门(1)
开发语言·c++·算法