2024.2.15力扣每日一题——二叉树的层序遍历2

2024.2.15

      • 题目来源
      • 我的题解
        • [方法一 普通层序遍历转置 或者 利用List的插入式添加](#方法一 普通层序遍历转置 或者 利用List的插入式添加)

题目来源

力扣每日一题;题序:107

我的题解

方法一 普通层序遍历转置 或者 利用List的插入式添加
  1. 将普通层序遍历得到的结果,逆序一下就是结果。
  2. List.add(0,element),相当于头插法
    时间复杂度 :O(n)
    空间复杂度:O(n)
java 复制代码
//使用普通层序遍历转置 
public List<List<Integer>> levelOrderBottom(TreeNode root) {
    List<List<Integer>> temp=new ArrayList<>();
    if(root==null)
        return temp;
    Queue<TreeNode> queue=new LinkedList<>();
    queue.offer(root);
    while(!queue.isEmpty()){
        int sz=queue.size();
        List<Integer> l=new ArrayList<>();
        for(int i=0;i<sz;i++){
            TreeNode t=queue.poll();
            l.add(t.val);
            if(t.left!=null)
                queue.offer(t.left);
            if(t.right!=null)
                queue.offer(t.right);
        }
        temp.add(l);
    }
    //逆序
    List<List<Integer>> res=new ArrayList<>();
    for(int i=temp.size()-1;i>=0;i--){
        res.add(temp.get(i));
    }
    return res;
}
java 复制代码
//使用List的插入式添加
public List<List<Integer>> levelOrderBottom(TreeNode root) {
   List<List<Integer>> temp=new ArrayList<>();
   if(root==null)
       return temp;
   Queue<TreeNode> queue=new LinkedList<>();
   queue.offer(root);
   while(!queue.isEmpty()){
       int sz=queue.size();
       List<Integer> l=new ArrayList<>();
       for(int i=0;i<sz;i++){
           TreeNode t=queue.poll();
           l.add(t.val);
           if(t.left!=null)
               queue.offer(t.left);
           if(t.right!=null)
               queue.offer(t.right);
       }
       //头插法
       temp.add(0,l);
   }
   return temp;
}

有任何问题,欢迎评论区交流,欢迎评论区提供其它解题思路(代码),也可以点个赞支持一下作者哈😄~

相关推荐
dying_man几秒前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel几秒前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
海棠一号16 分钟前
JAVA理论第五章-JVM
java·开发语言·jvm
eternal__day32 分钟前
Spring Cloud 多机部署与负载均衡实战详解
java·spring boot·后端·spring cloud·负载均衡
颜淡慕潇37 分钟前
Redis 实现分布式锁:深入剖析与最佳实践(含Java实现)
java·redis·分布式
程序员秘密基地43 分钟前
基于vscode,idea,java,html,css,vue,echart,maven,springboot,mysql数据库,在线考试系统
java·vue.js·spring boot·spring·web app
何中应44 分钟前
【设计模式-5】设计模式的总结
java·后端·设计模式
草莓熊Lotso1 小时前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
KyollBM1 小时前
【CF】Day75——CF (Div. 2) B (数学 + 贪心) + CF 882 (Div. 2) C (01Trie | 区间最大异或和)
c语言·c++·算法
吾日三省吾码1 小时前
Spring 团队详解:AOT 缓存实践、JSpecify 空指针安全与支持策略升级
java·spring·缓存