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;
}
相关推荐
Gu_shiwww5 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长6 小时前
C语言---循环结构
c语言·开发语言·算法
程序猿编码7 小时前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备
_不会dp不改名_8 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls8 小时前
C语言打印爱心
c语言·开发语言·算法
西阳未落8 小时前
C语言柔性数组详解与应用
c语言·开发语言·柔性数组
吃着火锅x唱着歌8 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun8 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌9 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
小莞尔11 小时前
【51单片机】【protues仿真】基于51单片机数控直流稳压电源系统
c语言·stm32·单片机·嵌入式硬件·51单片机