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;
}
相关推荐
flashlight_hi3 小时前
LeetCode 分类刷题:404. 左叶子之和
javascript·算法·leetcode
代码雕刻家4 小时前
C语言的左对齐符号-
c语言·开发语言
小白程序员成长日记4 小时前
2025.11.19 力扣每日一题
算法·leetcode·职场和发展
star learning white6 小时前
xmC语言8
c语言·开发语言·算法
青小俊6 小时前
【代码随想录c++刷题】-二分查找 移除元素 有序数组的平方 - 第一章 数组 part 01
c++·算法·leetcode
赖small强7 小时前
【Linux C/C++开发】第16章:多线程编程基础
linux·c语言·c++·多线程编程·进程和线程的本质区别
nono牛7 小时前
Android Binder C/C++ 层详解与实践
android·c语言·binder
倦王7 小时前
力扣日刷251120
算法·leetcode·职场和发展
cpp_25019 小时前
P1765 手机
数据结构·c++·算法·题解·洛谷
雨落在了我的手上9 小时前
C语言入门(十九):指针(5)
c语言