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;
}
相关推荐
墨染点香2 小时前
LeetCode 刷题【144. 二叉树的前序遍历】
数据结构·算法·leetcode
cynicme7 小时前
力扣3318——计算子数组的 x-sum I(偷懒版)
java·算法·leetcode
ACP广源盛139246256738 小时前
(ACP广源盛)GSV6172---MIPI/LVDS 信号转换为 Type-C/DisplayPort 1.4/HDMI 2.0 并集成嵌入式 MCU
c语言·开发语言·单片机·嵌入式硬件·音视频
im_AMBER9 小时前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
是苏浙12 小时前
零基础入门C语言之C语言内存函数
c语言·开发语言
2301_8079973814 小时前
代码随想录-day26
数据结构·c++·算法·leetcode
闭着眼睛学算法14 小时前
【双机位A卷】华为OD笔试之【排序】双机位A-银行插队【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·c语言·javascript·c++·python·算法·华为od
小欣加油15 小时前
leetcode 3318 计算子数组的x-sum I
c++·算法·leetcode·职场和发展
海琴烟Sunshine16 小时前
leetcode 190. 颠倒二进制位 python
python·算法·leetcode
AI柠檬16 小时前
C语言基于MPI并行计算矩阵的乘法
c语言·c++·算法