leetcode做题笔记102. 二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

思路一:递归

cpp 复制代码
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    int** ans=(int**)malloc(sizeof(int*)*2000);
    *returnSize=0;
    if(!root) return NULL;
    int columnSizes[3000];
    struct TreeNode* queue[3000];
    int rear=0;int head=0;
    queue[rear++]=root;

    while(rear!=head){
        ans[(*returnSize)]=(int*)malloc(sizeof(int)*(rear-head));
        columnSizes[(*returnSize)]=rear-head;
        int start=head;
        head=rear;
        for(int i=start;i<head;i++){
            ans[(*returnSize)][i-start]=queue[i]->val;
            if(queue[i]->left) queue[rear++]=queue[i]->left;
            if(queue[i]->right) queue[rear++]=queue[i]->right;
        }
        (*returnSize)++;
       
    }
    *returnColumnSizes=(int*)malloc(sizeof(int)*(*returnSize));
    for(int i=0;i<*returnSize;i++) (*returnColumnSizes)[i]=columnSizes[i];
    return ans;
}

分析:

本题要求二叉树的层序遍历,可想到使用BFS算法,将二叉树每层放入数组中最后输出数组,可想到利用队列插入队尾删除队首的特性模拟队列记录每层的数再输出

总结:

本题考察二叉树的层序遍历,利用队列的特性可以解决

相关推荐
严肃小白兔2 分钟前
MATLAB 数值计算中的精度与误差问题:浮点运算、误差传播与数值稳定性
人工智能·算法·matlab
青少儿编程课堂1 小时前
蓝桥杯青少组图形化省考报名倒计时·全国青少年信息素养大赛·电子学会图形化考级:校园黑白棋人机对战解析
c++·python·算法·bfs·信息学竞赛
只愿云淡风清2 小时前
正则表达式学习笔记 02:基础语法
笔记·学习·正则表达式
jktantan2 小时前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·后端·算法·spring cloud·系统架构
希和202712 小时前
考研英语阅读词汇笔记|城市野径、抄近道步道(非正式小路)
笔记·考研
Dream it possible!15 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊15 小时前
算法之双指针系列(一)
算法·leetcode
一个人旅程~15 小时前
关于imac27inch因改短用户名导致混合硬盘和系统崩溃的问题分析与故障解决
经验分享·笔记·macos·新浪微博
十二15 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
心祭丫丫16 小时前
【每天一个 Python 小案例17】Python 实现通讯录
开发语言·人工智能·笔记·python·学习