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;
    }
相关推荐
SimonKing5 分钟前
震惊:怎么回事,opencode一轮对话耗尽免费额度
java·后端·程序员
装不满的克莱因瓶9 分钟前
【SpringAI Alibaba】ReactAgent响应SSE实时流式传输案例实战
java·人工智能·ai·sse·springai
杨凯凡12 分钟前
Spring Boot 文件上传怎么做才安全?流式落盘、路径校验与数据库一致性实战
java·spring boot·文件上传·后端安全·数据库一致性
这个昵称不容易38 分钟前
旅游管理系统的设计与实现(SpringBoot + MySQL + Vue 前后端分离)
java·springboot·毕设
Rain的Java大神之路39 分钟前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode
NEFU_Jyj1 小时前
贝尔数(组合数学)
算法
希和20271 小时前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
Pniubi2 小时前
力扣73 矩阵置零
算法·leetcode·矩阵
天天被压力2 小时前
【A股分钟级高频数据完全手册 #11】券商实时行情数据接口:实时交易(券商源)接入与字段
java·人工智能·python
天天被压力2 小时前
【A股分钟级高频数据完全手册 #12】股票五档盘口数据接口:买卖五档实时盘口解析
java·人工智能·python