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;
}
相关推荐
梁下轻语的秋缘24 分钟前
每日c/c++题 备战蓝桥杯(洛谷P1115 最大子段和)
c语言·c++·蓝桥杯
是代码侠呀1 小时前
从前端视角看网络协议的演进
leetcode·开源·github·github star·github 加星
C_Liu_2 小时前
C语言:深入理解指针(3)
c语言·数据结构·算法
南玖yy2 小时前
C/C++ 内存管理深度解析:从内存分布到实践应用(malloc和new,free和delete的对比与使用,定位 new )
c语言·开发语言·c++·笔记·后端·游戏引擎·课程设计
刃神太酷啦3 小时前
类和对象(1)--《Hello C++ Wrold!》(3)--(C/C++)
java·c语言·c++·git·算法·leetcode·github
HY小海4 小时前
【数据结构】双链表
c语言·开发语言·数据结构·学习
I AM_SUN4 小时前
994. 腐烂的橘子
数据结构·c++·算法·leetcode·职场和发展
真的想上岸啊5 小时前
c语言第一个小游戏:贪吃蛇小游戏03
c语言·开发语言·算法
小狗祈祷诗5 小时前
day18-数据结构引言
c语言·数据结构
Tisfy5 小时前
LeetCode 3341.到达最后一个房间的最少时间 I:Dijkstra算法(类似深搜)-简短清晰的话描述
leetcode··最短路·dijkstra·题解·迪杰斯特拉