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;
}
相关推荐
让我上个超影吧4 小时前
【力扣26&80】删除有序数组中的重复项
算法·leetcode
鑫—萍5 小时前
嵌入式开发学习——STM32单片机入门教程
c语言·驱动开发·stm32·单片机·嵌入式硬件·学习·硬件工程
LYS_06185 小时前
RM赛事C型板九轴IMU解算(4)(卡尔曼滤波)
c语言·开发语言·前端·卡尔曼滤波
漫随流水6 小时前
leetcode回溯算法(78.子集)
数据结构·算法·leetcode·回溯算法
We་ct6 小时前
LeetCode 151. 反转字符串中的单词:两种解法深度剖析
前端·算法·leetcode·typescript
wen__xvn7 小时前
代码随想录算法训练营DAY25第七章 回溯算法 part04
算法·leetcode·深度优先
June bug8 小时前
(#字符串处理)字符串中第一个不重复的字母
python·leetcode·面试·职场和发展·跳槽
AlenTech8 小时前
197. 上升的温度 - 力扣(LeetCode)
算法·leetcode·职场和发展
源代码•宸10 小时前
Leetcode—404. 左叶子之和【简单】
经验分享·后端·算法·leetcode·职场和发展·golang·dfs
WBluuue10 小时前
数据结构与算法:dp优化——优化尝试和状态设计
c++·算法·leetcode·动态规划