【hot100】199二叉树的右视图

一、思路

这题和二叉树的层序遍历几乎一样,就是在层序遍历的基础上,只把每层最右边的元素加入list里即可

二、记忆

1.双端队列中有记录长度的属性,可以直接获取

Deque<TreeNode> treeNodes = new LinkedList<>();

int currentsize = treeNodes.size();

三、代码

复制代码
public List<Integer> rightSideView(TreeNode root){
        if (root==null) return new ArrayList<>();
        Deque<TreeNode> treeNodes = new LinkedList<>();
        List<Integer> ret = new ArrayList<>();
        treeNodes.add(root);
        while(!treeNodes.isEmpty()){
            int currentsize = treeNodes.size();
            for (int i = 0;i<currentsize;i++){
                TreeNode temp = treeNodes.pollFirst();
                if (i==currentsize-1) ret.add(temp.val);//每行最后一个树加入
                if (temp.left!=null){
                    treeNodes.addLast(temp.left);
                }
                if (temp.right!=null){
                    treeNodes.addLast(temp.right);
                }
            }
        }
        return ret;
    }
相关推荐
zizisuo1 小时前
解决在使用Lombok时maven install 找不到符号的问题
java·数据库·maven
笨蛋少年派1 小时前
JAVA基础语法
java·开发语言
Haooog2 小时前
654.最大二叉树(二叉树算法)
java·数据结构·算法·leetcode·二叉树
我真的是大笨蛋2 小时前
依赖倒置原则(DIP)
java·设计模式·性能优化·依赖倒置原则·设计规范
东方芷兰2 小时前
JavaWeb 课堂笔记 —— 20 SpringBootWeb案例 配置文件
java·开发语言·笔记·算法·log4j·intellij-idea·lua
Roye_ack3 小时前
【项目实战 Day9】springboot + vue 苍穹外卖系统(用户端订单模块 + 商家端订单管理模块 完结)
java·vue.js·spring boot·后端·mybatis
人间有清欢3 小时前
java数据权限过滤
java·mybatis·权限控制·数据过滤
A阳俊yi3 小时前
Spring——声明式事务
java·数据库·spring
我要精通C++3 小时前
lua虚拟机的垃圾回收机制
java·开发语言
22jimmy3 小时前
MyBatis动态sql
java·开发语言·mybatis