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;
}
相关推荐
大侠归来1 小时前
C 语言 | 在函数中操作数组
c语言·c++·算法
小师兄吃牛肉8 小时前
C语言篇:宏
c语言·开发语言
炸膛坦客9 小时前
单片机开发工具篇:(十四)配置输出 .map 文件及其本地路径
c语言·单片机·嵌入式硬件
kakakahahahaha9 小时前
Windows C盘临时文件清理:%temp%、Windows Temp、Prefetch、Windows.old与hiberfil.sys处理指南
c语言·开发语言·windows
Navigator_Z11 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
lvwangshu11 小时前
登录日志 题解
数据结构·线段树·题解·技巧·性质题·思维好题·细节题
殷色玫瑰12 小时前
C/C++ 内存管理详解:从内存分布到 new/delete 底层原理
java·linux·c语言·c++
C++ 老炮儿的技术栈12 小时前
main函数之后的调用
c语言·c++·人工智能·qt·mfc·c
青山木13 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
小师兄吃牛肉14 小时前
C语言指针进阶全解析
java·c语言·算法