特定深度节点链表

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

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

objectivec 复制代码
#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;
}
相关推荐
Ayanami_Reii7 分钟前
进阶数据结构应用-维护序列
数据结构·算法·线段树
CoderYanger18 分钟前
C.滑动窗口-越长越合法/求最短/最小——2904. 最短且字典序最小的美丽子字符串
java·开发语言·数据结构·算法·leetcode·1024程序员节
别动哪条鱼1 小时前
FFmpeg API 数据结构及其详细说明:
数据结构·ffmpeg·音视频·aac
Ayanami_Reii1 小时前
进阶数据结构-线段树
数据结构·算法·线段树
liu****1 小时前
11.字符函数和字符串函数(一)
linux·运维·c语言·开发语言·数据结构·算法
!chen1 小时前
SQL Server 2025 新功能概览
数据结构
埃伊蟹黄面1 小时前
双指针算法
数据结构·c++·算法
java修仙传1 小时前
力扣hot100:反转链表
算法·leetcode·链表
Elias不吃糖1 小时前
Leetcode-10.正则表达式匹配(暴力 或 记忆暴力)
数据结构·c++·算法·leetcode·深度优先
小年糕是糕手2 小时前
【C++】类和对象(四) -- 取地址运算符重载、构造函数plus
c语言·开发语言·数据结构·c++·算法·leetcode·蓝桥杯