C语言 | Leetcode C语言题解之第559题N叉树的最大深度

题目:

题解:

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     int numChildren;
 *     struct Node** children;
 * };
 */

int maxDepth(struct Node* root) {
    if (!root) {
        return 0;
    }

    int depth = 0;
    // 创建空队列
    const int qCap = 10e4 + 1;
    struct Node **q = (struct Node **)malloc(sizeof(struct Node*) * qCap);
    int front = 0, rear = 0;
    // 队列初始化
    q[rear] = root;
    rear = (rear + 1) % qCap;
    int qSize = (rear - front + qCap) % qCap;

    while (qSize != 0) {
        while (qSize > 0) {
            struct Node *n = q[front];
            front = (front + 1) % qCap;

            struct Node **children = n->children;
            for (int i = 0; i < n->numChildren; i++) {
                q[rear] = children[i];
                rear = (rear + 1) % qCap;
            }
            qSize--;
        }
        qSize = (rear - front + qCap) % qCap;
        depth++;
    }
    free(q);
    return depth;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值