特定深度节点链表

题目链接:力扣(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;
}
相关推荐
啦啦啦啦啦zzzz13 小时前
数据结构:二叉树的线索化
数据结构·算法
如竟没有火炬14 小时前
寻找峰值——二分
java·开发语言·数据结构·python·算法·散列表
he___H16 小时前
B、B+树和vue部分知识
数据结构·vue.js·b树
hai31524754317 小时前
结构化编程:AI工业化编程的探索
数据结构·自然语言处理·硬件工程·动态规划·集成学习
2401_8685347817 小时前
2026年5月系统分析
数据结构·python·tornado
袋鼠云数栈18 小时前
数栈 V7.0 多模态数据智能平台:打造 AI-Ready 的企业数据底座
大数据·数据结构·数据库·人工智能·数据治理·多模态
迈巴赫车主19 小时前
优先队列(PriorityQueue)
数据结构·算法
Boom_Shu19 小时前
构造函数程序
数据结构·算法
Lucky_ldy20 小时前
数据结构从入门到精通:链表
数据结构·链表
邪修king20 小时前
C++map_set封装 : 红黑树底层迭代器以及仿函数的运用
android·c语言·数据结构·c++·b树