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;
    }
相关推荐
JAVA面经实录9175 分钟前
IDEA 开发知识
java·intellij-idea·idea
于樱花森上飞舞9 分钟前
【Redis】哨兵详解
java·开发语言·数据库·redis
Navigator_Z11 分钟前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.15 分钟前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
2601_9538246121 分钟前
基于SSM的水果超市管理系统
java·tomcat·maven
guo_wen_qiang23 分钟前
springboot如何自定义一个启动器starter
java·spring boot·intellij-idea
许彰午27 分钟前
55-字典缓存与通知SPI
java·低代码·架构
captain37632 分钟前
HTTP(2)
java·网络·http·java-ee
徐子童34 分钟前
介绍MVCC机制
java·mysql·面试题·秋招·并发·mvcc
Wang's Blog35 分钟前
Java 项目实战: 外卖平台-启用禁用员工账号与Long精度丢失修复
java·服务器