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;
    }
相关推荐
Wang's Blog1 分钟前
Java 接入Redis: 字符串与哈希类型操作命令
java·服务器·redis
智慧物业老杨4 小时前
物业数字化落地思考:真正的转型,是底层数据秩序的重构
java·大数据·人工智能·微服务·系统架构
萧西待水6 小时前
奥赛一本通 1447 靶形数独
算法·深度优先
星空7 小时前
金蝶苍穹build.gradle配置
java·build.gradle
泯泷8 小时前
那段文字是谁删的?Yjs 14 正式版之前,一套删除归属方案的实现与边界
前端·javascript·算法
hold?fish:palm8 小时前
34 合并K个升序链表
javascript·算法·链表
步行cgn10 小时前
Spring 基于 XML 的自动装配:byName 详解
java·后端·spring
Navigator_Z10 小时前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
大帅点兵10 小时前
Apache Ant 1.9.9 完整讲解
java
LuTshoes11 小时前
spring ai 实战 手搓 PlaneExecuteAgent
java·人工智能·spring·ai