力扣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的算法实验室3 小时前
SEVC,城市灾害环境下应急物流的帕累托归档引导式多目标路径规划
算法
维克兜率天3 小时前
【维克】布林带:通道类指标的“量化基石“
人工智能·python·算法
风落青芜4 小时前
C++入门:类和对象(二)
开发语言·数据结构·c++·算法
wuyk5554 小时前
AI 时代的嵌入式该怎么学-11-C不是语法是对内存的显式建模
c语言·开发语言·stm32·单片机·嵌入式硬件·mcu·算法
吞下星星的少年·-·4 小时前
LeetCode 热题 100 最长连续序列(哈希表)
算法·leetcode·散列表
风落青芜5 小时前
C++入门:类和对象(三)
开发语言·数据结构·c++·算法
Pniubi6 小时前
力扣25.K个一组反转链表
算法·leetcode·链表
16月6日-晴6 小时前
力扣22题,括号生成
算法
老唐7777 小时前
具身智能视觉感知详解:从图像识别到机器人环境理解,核心技术、算法架构与应用实践
人工智能·深度学习·算法·机器人·大模型·具身智能