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

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

相关推荐
圣保罗的大教堂10 分钟前
leetcode 2799. 统计完全子数组的数目 中等
leetcode
264玫瑰资源库10 分钟前
问道数码兽 怀旧剧情回合手游源码搭建教程(反查重优化版)
java·开发语言·前端·游戏
SsummerC17 分钟前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
pwzs20 分钟前
Java 中 String 转 Integer 的方法与底层原理详解
java·后端·基础
东阳马生架构22 分钟前
Nacos简介—2.Nacos的原理简介
java
普if加的帕35 分钟前
java Springboot使用扣子Coze实现实时音频对话智能客服
java·开发语言·人工智能·spring boot·实时音视频·智能客服
YuCaiH1 小时前
数组理论基础
笔记·leetcode·c·数组
爱喝一杯白开水1 小时前
SpringMVC从入门到上手-全面讲解SpringMVC的使用.
java·spring·springmvc
王景程1 小时前
如何测试短信接口
java·服务器·前端
2301_807611491 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯