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;
}
相关推荐
Darkwanderor1 分钟前
使用管道实现进程间通信 (IPC, Inter-Process Communitation)
linux·c语言·c++
冻柠檬飞冰走茶14 分钟前
PTA基础编程题目集 7-37 整数分解为若干项之和(C语言实现)
c语言·开发语言·数据结构·算法
luj_176812 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
画面无声12 小时前
STM32的SPI通信原理与练习记录
c语言·stm32·单片机·嵌入式硬件·学习
weixin_4568083812 小时前
【沁恒蓝牙开发】IAP升级流程
c语言·单片机·嵌入式硬件
geats人山人海14 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
影视飓风TIM15 小时前
Linux下C语言缓冲区原理 + Git版本控制
linux·c语言·git
皓月斯语15 小时前
B2118 验证子串
c++·题解
冻柠檬飞冰走茶16 小时前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法
Hi李耶16 小时前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展