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 小时前
LeetCode Hot100 C++ 哈希 1.两数之和
c++·算法·leetcode·哈希算法
杰九1 小时前
【算法题】53. 最大子数组和-力扣(LeetCode)
算法·leetcode·动态规划
陈序缘1 小时前
LeetCode讲解篇之75. 颜色分类
算法·leetcode·职场和发展
予早2 小时前
LeetCode 149. 直线上最多的点数
算法·leetcode
街 三 仔2 小时前
【C语言零基础入门篇 - 15】:单链表
c语言·开发语言
苏格拉没有底1112 小时前
数据结构——顺序表、链表
c语言·开发语言·数据结构·笔记·学习·算法·链表
进击的_鹏2 小时前
数据结构之顺序表
c语言·数据结构
抓哇能手2 小时前
王道408考研数据结构-树与二叉树-第五章-第三四节
c语言·数据结构·考研·算法·408
Ddddddd_1583 小时前
C++ | Leetcode C++题解之第432题全O(1)的数据结构
c++·leetcode·题解