力扣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;
    }
}
相关推荐
星子yu36 分钟前
【学习】怎么学好数据结构
数据结构·学习
alphaTao2 小时前
LeetCode 每日一题 2026/7/6-2026/7/12
算法·leetcode
想吃火锅10052 小时前
【leetcode】56.合并区间js
算法·leetcode·职场和发展
imuliuliang2 小时前
可合并堆在多任务调度中的优势与实现技巧7
算法
学究天人2 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷6)
网络·算法·数学建模·动态规划·几何学·图论·拓扑学
wabs6662 小时前
关于动态规划【力扣72.编辑距离的思考】
算法·leetcode·动态规划
用户333239768842 小时前
我做了一个 RepoMind:让 AI 写架构前,先去看看真实开源项目
算法
chh5632 小时前
C++--list
开发语言·数据结构·c++·学习·算法·list
killerbasd2 小时前
总结 7。10
人工智能·算法·机器学习
林间码客3 小时前
RAG系统评估指南:从入门到实践
人工智能·算法·机器学习