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;
}
相关推荐
find1star13 小时前
LeetCode 141:环形链表
java·算法·leetcode·链表
LB211213 小时前
力扣160 21 86
算法·leetcode·职场和发展
a1879272183114 小时前
【算法】动态规划第二篇:双序列 DP 三课——继承、计步与断链
算法·leetcode·动态规划·dp·回溯·暴力·算法讲解
Nil20821 小时前
leetcode 994腐烂的橘子
算法·leetcode·职场和发展
热心网友俣先生1 天前
2026国赛C题:五年命题规律与预测
java·c语言·前端·数学建模
wuminyu1 天前
Linux内核线程调度与虚拟线程调度机制系统级深度剖析
java·linux·c语言·jvm·c++
血小板要健康1 天前
队列 + 宽搜(BFS):二叉树层序遍历 算法总结
java·数据结构·笔记·算法·leetcode·宽度优先
不会就选b1 天前
算法日常・每日刷题--<贪心>3
数据结构·算法·leetcode
ysu_03141 天前
03-双链表与循环链表
c语言·数据结构·链表
学习星球1 天前
编辑距离——二维 DP 的“最小操作“艺术
c++·leetcode·java-consul