特定深度节点链表

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

经典BFS与简单链表结合的题目。

#define MAX_DEPTH (1000)

struct ListNode** listOfDepth(struct TreeNode* tree, int* returnSize)
{
    *returnSize = 0;
    struct ListNode **ans = (struct ListNode **)malloc(sizeof(struct ListNode*) * MAX_DEPTH);
    struct TreeNode *quene[MAX_DEPTH];
    struct ListNode *pre = NULL;
    int front = 0;
    int rear = 0;

    if (tree) {
        quene[rear++] = tree;
    }
    while (front != rear) {
        int cnt = rear - front;
        for (int i = 0; i < cnt; i++) {
            if (i == 0) {
                ans[(*returnSize)] = (struct ListNode*)malloc(sizeof(struct ListNode)); // 每层的链表头
                pre = ans[(*returnSize)++];
                pre->val = quene[front]->val;
                pre->next = NULL;
            } else {
                struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
                node->val = quene[front]->val;
                node->next = NULL;
                pre->next = node;
                pre = pre->next;
            }
            if (quene[front]->left) {
                quene[rear++] = quene[front]->left;
            }
            if (quene[front]->right) {
                quene[rear++] = quene[front]->right;
            }
            front++;
        }
    }
    return ans;
}

你可能感兴趣的:(链表,数据结构,BFS)