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

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

相关推荐
StickToForever3 小时前
第4章 信息系统架构(五)
经验分享·笔记·学习·职场和发展
南山十一少3 小时前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
427724005 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo5 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦5 小时前
常用的 JVM 参数:配置与优化指南
java·jvm
计算机小白一个5 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
万事可爱^5 小时前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
欧了1117 小时前
洛谷P9240 [蓝桥杯 2023 省 B] 冶炼金属
职场和发展·蓝桥杯·洛谷·蓝桥杯大学b组c语言
大数据追光猿7 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!8 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode