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;
}

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

相关推荐
亲爱的马哥几秒前
重磅更新 | 填鸭表单TDuckX2.9发布!
java
Java中文社群2 分钟前
26届双非上岸记!快手之战~
java·后端·面试
whitepure7 分钟前
万字详解Java中的面向对象(二)——设计模式
java·设计模式
whitepure9 分钟前
万字详解Java中的面向对象(一)——设计原则
java·后端
Xの哲學32 分钟前
Perf使用详解
linux·网络·网络协议·算法·架构
2301_7930868736 分钟前
SpringCloud 02 服务治理 Nacos
java·spring boot·spring cloud
想不明白的过度思考者42 分钟前
数据结构(排序篇)——七大排序算法奇幻之旅:从扑克牌到百亿数据的魔法整理术
数据结构·算法·排序算法
回家路上绕了弯44 分钟前
MySQL 详细使用指南:从入门到精通
java·mysql
小七rrrrr1 小时前
动态规划法 - 53. 最大子数组和
java·算法·动态规划
code小毛孩1 小时前
leetcodehot100 矩阵置零
算法