45、二叉树-二叉树的右视图

思路

层序遍历 从左向右遍历每一层取最后一个数,代码如下:

java 复制代码
public List<Integer> rightSideView(TreeNode root) {
        if (root==null){
            return new ArrayList<>();
        }
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> list = new ArrayList<>();
        TreeNode cur=root;
        queue.add(cur);
      
        while (!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                cur = queue.poll();
                if (i==size-1){
                    list.add(cur.val);
                }
                if (cur.left!=null){
                    queue.add(cur.left);
                }
                if (cur.right!=null){
                    queue.add(cur.right);
                }
            }
        }
        return list;
    }
相关推荐
先做个垃圾出来………1 天前
3640. 三段式数组 II
数据结构·算法
014.1 天前
2025最新jenkins保姆级教程!!!
java·运维·spring boot·spring·jenkins
浣熊8881 天前
天机学堂虚拟机静态ip无法使用(重启后ip:192.168.150.101无法使用连接Mobaxterm数据库等等,或者无法使用修改之后的Hosts域名去访问nacos,jenkins)
java·微服务·虚拟机·天机学堂·重启之后静态ip用不了
心 -1 天前
java八股文IOC
java
tankeven1 天前
HJ93 数组分组
c++·算法
Σίσυφος19001 天前
LM 在 PnP(EPnP / P3P)的应用
算法
陈天伟教授1 天前
人工智能应用- 人工智能交叉:01. 破解蛋白质结构之谜
人工智能·神经网络·算法·机器学习·推荐算法
LightYoungLee1 天前
General-behavior interview tutorials
算法
I_LPL1 天前
day34 代码随想录算法训练营 动态规划专题2
java·算法·动态规划·hot100·求职面试
亓才孓1 天前
【MyBatis Exception】Public Key Retrieval is not allowed
java·数据库·spring boot·mybatis