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

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

相关推荐
Pluto_CSND1 小时前
Java中的静态代理与动态代理(Proxy.newProxyInstance)
java·开发语言
百***46452 小时前
Java进阶-在Ubuntu上部署SpringBoot应用
java·spring boot·ubuntu
serve the people2 小时前
Prompts for Chat Models in LangChain
java·linux·langchain
一叶飘零_sweeeet2 小时前
不止于 API 调用:解锁 Java 工具类设计的三重境界 —— 可复用性、线程安全与性能优化
java·工具类
cynicme3 小时前
力扣3228——将 1 移动到末尾的最大操作次数
算法·leetcode
熬了夜的程序员3 小时前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
随意起个昵称3 小时前
【递归】二进制字符串中的第K位
c++·算法
测试老哥3 小时前
软件测试之单元测试知识总结
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
mjhcsp4 小时前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
立志成为大牛的小牛4 小时前
数据结构——四十一、分块查找(索引顺序查找)(王道408)
数据结构·学习·程序人生·考研·算法