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;
    }
相关推荐
豆豆酱6 分钟前
Informer方法论详解
算法
槐月初叁9 分钟前
多模态推荐系统指标总结
算法
迪小莫学AI26 分钟前
LeetCode 2588: 统计美丽子数组数目
算法·leetcode·职场和发展
昂子的博客33 分钟前
热门面试题第十天|Leetcode150. 逆波兰表达式求值 239. 滑动窗口最大值 347.前 K 个高频元素
算法
Forget the Dream1 小时前
设计模式之迭代器模式
java·c++·设计模式·迭代器模式
大丈夫在世当日食一鲲1 小时前
Java中用到的设计模式
java·开发语言·设计模式
A-Kamen1 小时前
Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现与实战指南
java·spring boot·后端
练川1 小时前
Stream特性(踩坑):惰性执行、不修改原始数据源
java·stream
狂奔小菜鸡1 小时前
Java运行时数据区
java·jvm·后端
trymoLiu1 小时前
SpringBoot 实现 RSA+AES 自动接口解密!
java·spring boot