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

2024.2.14

      • 题目来源
      • 我的题解
        • [方法一 递归实现(前序遍历+记录深度)](#方法一 递归实现(前序遍历+记录深度))
        • [方法二 非递归实现(队列)](#方法二 非递归实现(队列))

题目来源

力扣每日一题;题序:102

我的题解

方法一 递归实现(前序遍历+记录深度)

在递归遍历时记录节点所在的深度,然后把值加入到对应的深度的链表中。并利用List的set方法更新对应层次的元素List
时间复杂度 :O(n)。遍历所有节点
空间复杂度:O(n)。递归空间的大小

java 复制代码
public List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> res=new ArrayList<>();
    if(root==null)
        return res;
    levelOrder1(root,0,res);
    return res;
}
public void levelOrder1(TreeNode root,int level,List<List<Integer>> res){
    if(root==null)
        return ;
    // 已经遍历过的层次
    if(res.size()>level){
        List<Integer> list=res.get(level);
        list.add(root.val);
        res.set(level,list);
    // 还未遍历的层次 
    }else{
        List<Integer> list=new ArrayList<>();
        list.add(root.val);
        res.add(list);
    }
    levelOrder1(root.left,level+1,res);
    levelOrder1(root.right,level+1,res);
}
方法二 非递归实现(队列)

利用队列的先进先出的特性,将每一行的节点从左到右存入队列中,然后以此取出进行遍历,再加入相应的子节点。
时间复杂度:O(n)。需要遍历所有节点

空间复杂度:O(n)。队列需要的空间

java 复制代码
public List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> res=new ArrayList<>();
    if(root==null)
        return res;
    Queue<TreeNode> queue=new LinkedList<>();
    queue.offer(root);
    while(!queue.isEmpty()){
        int sz=queue.size();
        List<Integer> temp=new ArrayList<>();
        for(int i=0;i<sz;i++){
            TreeNode t=queue.poll();
            temp.add(t.val);
            if(t.left!=null)
                queue.offer(t.left);
            if(t.right!=null)
                queue.offer(t.right);
        }
        res.add(temp);
    }
    return res;
}

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

相关推荐
2401_8914821711 分钟前
多平台UI框架C++开发
开发语言·c++·算法
SuniaWang23 分钟前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》
java·前端·人工智能·spring boot·后端·spring·架构
sheji341630 分钟前
【开题答辩全过程】以 基于springboot的扶贫系统为例,包含答辩的问题和答案
java·spring boot·后端
88号技师33 分钟前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t1987512834 分钟前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神35 分钟前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
m0_726965981 小时前
面面面,面面(1)
java·开发语言
x_xbx1 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
Darkwanderor1 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920742 小时前
分布式系统安全通信
开发语言·c++·算法