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;
    }
相关推荐
倚肆10 小时前
Spring WebSocket 的 MessageBrokerRegistry 与 StompEndpointRegistry 配置参数详解
java·websocket
tankeven10 小时前
HJ91 走方格的方案数
c++·算法
俩娃妈教编程10 小时前
2024 年 09 月 二级真题(2)--小杨的矩阵
c++·算法·gesp真题
弹简特10 小时前
【JavaEE09-后端部分】SpringMVC04-SpringMVC第三大核心-处理响应和@RequestMapping详解
java·spring boot·spring·java-ee·tomcat
漫霂10 小时前
Redis在Spring Boot中的应用
java·后端
浅念-10 小时前
C++ STL vector
java·开发语言·c++·经验分享·笔记·学习·算法
小雨中_10 小时前
2.8 策略梯度(Policy Gradient)算法 与 Actor-critic算法
人工智能·python·深度学习·算法·机器学习
m0_5312371710 小时前
C语言-if/else,switch/case
c语言·数据结构·算法
亓才孓10 小时前
[Mybatis]MyBatisSystemException(由于Connection的encoding引起的)
java·开发语言·mybatis
Never_Satisfied11 小时前
在c#中,如何在字符串的第x个字符位置插入字符
java·开发语言·c#