Leetcode 107:二叉树的层次遍历II

给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)。

思路:翻转title102的结果即可。

java 复制代码
//层次遍历二叉树
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result=new ArrayList();
        //借助队列
        Queue<TreeNode> queue=new LinkedList();
        if(root!=null){
            queue.add(root);
        }

        while (!queue.isEmpty()){
            int size=queue.size();   //记录每层个数
            List<Integer> list=new ArrayList();

            for(int i=0;i<size;i++){
                TreeNode node=queue.poll();
                list.add(node.val);
                if(node.left!=null){
                    queue.add(node.left);
                }
                if(node.right!=null){
                    queue.add(node.right);
                }
            }
            result.add(list);
        }

        //翻转二维列表
        List<List<Integer>> res=new ArrayList();
        for(int i=result.size()-1;i>=0;i--){
            res.add(result.get(i));
        }
        return res;
    }
相关推荐
砍材农夫几秒前
spring|spring event|Spring内置事件驱动编程模型
java·数据库·spring
wuqingshun3141591 小时前
RabbitMQ 中无法路由的消息会去到哪里?
java
thefool1122662 小时前
Java 方法重载
java
这不小天嘛8 小时前
JAVA八股——J集合篇
java·开发语言
ysu_03149 小时前
05 | 持久化撤销提示非核心功能
算法·游戏程序
浮沉98710 小时前
二分查找算法概述&通用模板
算法
Keven_1111 小时前
算法札记:SPFA判负环算法的证明
算法
什巳11 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
豆瓣鸡11 小时前
RocketMQ学习-Spring Boot消息实践
java·spring boot·rocketmq