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;
    }
相关推荐
用户3721574261351 分钟前
Java 查找并高亮 Word 文字:精确查找及正则表达式模糊查找
java
zyseo819 分钟前
谷歌SEO 站内搜索优化实战:把站内搜索词变成关键词金矿
java·服务器·数据库
bug菌27 分钟前
🤔同事突然问我:Spring的注解 @Component 和 @Service 有何不同?
java·spring boot·后端
佳児素花痴╮31 分钟前
线程知识点
java·开发语言·jvm
镜子AI1 小时前
教培机构AI推荐系统实战:概念漂移检测算法——为什么“去年有效的推荐今年可能失效“
人工智能·算法
fundoit1 小时前
为什么需要 Access Token 和 ID Token 两个令牌
java·spring·架构·github·oauth2
鱼宵2 小时前
Spring AI 流式输出:Flux + SSE 打字机,回答不再干等三秒
java·人工智能·spring·sse·springai·流式输出
shaibdoio2 小时前
AI主动获客的意图识别工程实现:从规则匹配到模型微调
java·开发语言·人工智能·长沙瞬维ai
for_ever_love__2 小时前
MySQL 事务隔离级别讲透:MVCC、幻读与四个级别怎么选
java·数据库·mysql·事务·mvcc·不可重复读·幻读
垆边人似月.2 小时前
华为OD算法题:查找众数及中位数
数据结构·算法·leetcode