C语言 | Leetcode C语言题解之第429题N叉树的层序遍历

题目:

题解:

cpp 复制代码
#define MAX_LEVE_SIZE 1000
#define MAX_NODE_SIZE 10000

int** levelOrder(struct Node* root, int* returnSize, int** returnColumnSizes) {
    int ** ans = (int **)malloc(sizeof(int *) * MAX_LEVE_SIZE);
    *returnColumnSizes = (int *)malloc(sizeof(int) * MAX_LEVE_SIZE);
    if (!root) {
        *returnSize = 0;
        return ans;
    }
    struct Node ** queue = (struct Node **)malloc(sizeof(struct Node *) * MAX_NODE_SIZE);
    int head = 0, tail = 0;
    int level = 0;
    queue[tail++] = root;

    while (head != tail) {
        int cnt = tail - head;
        ans[level] = (int *)malloc(sizeof(int) * cnt);
        for (int i = 0; i < cnt; ++i) {
            struct Node * cur = queue[head++];
            ans[level][i] = cur->val;
            for (int j = 0; j < cur->numChildren; j++) {
                queue[tail++] = cur->children[j];
            }
        }
        (*returnColumnSizes)[level++] = cnt;
    }
    *returnSize = level;
    free(queue);
    return ans;
}
相关推荐
汤姆_5111 小时前
【c语言】深度理解指针4——sizeof和strlen
c语言·开发语言
杰杰批1 小时前
力扣热题100——矩阵
算法·leetcode·矩阵
_GR2 小时前
2025年蓝桥杯第十六届C&C++大学B组真题及代码
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
照海19Gin3 小时前
数据结构中的宝藏秘籍之广义表
c语言·数据结构·算法
加点油。。。。3 小时前
C语言高频面试题——strcpy与memcpy区别
c语言·开发语言
双叶8364 小时前
(51单片机)LCD显示数据存储(DS1302时钟模块教学)(LCD1602教程)(独立按键教程)(延时函数教程)(I2C总线认识)(AT24C02认识)
c语言·数据库·单片机·嵌入式硬件·mongodb·51单片机·nosql
那就摆吧4 小时前
数据结构-栈
android·java·c语言·数据结构
L_09074 小时前
【C】初阶数据结构10 -- 希尔排序
c语言·数据结构·排序算法
格里姆肖4 小时前
HAL库通过FATFS和SDIO+DMA写入SD卡数据错误
c语言·stm32·单片机
暖阳冷月海无涯4 小时前
数据结构-C语言版本(四)队列
c语言·数据结构