特定深度节点链表

题目链接:力扣(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;
}
相关推荐
漫随流水8 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
Titan202411 小时前
map和set的封装学习笔记
数据结构·c++
Yupureki12 小时前
《算法竞赛从入门到国奖》算法基础:动态规划-路径dp
数据结构·c++·算法·动态规划
重庆小透明13 小时前
力扣刷题【3】相交链表
算法·leetcode·链表
算法鑫探13 小时前
C语言实战:学生成绩统计与分析
c语言·数据结构·算法·新人首发
_日拱一卒14 小时前
LeetCode:最小覆盖字串
java·数据结构·算法·leetcode·职场和发展
郝学胜-神的一滴14 小时前
Qt6 + OpenGL 3.3 渲染环境搭建全指南:从空白窗口到专属渲染画布的优雅实现
数据结构·c++·线性代数·算法·系统架构·图形渲染
小肥米14 小时前
分块查找ASL公式推导,为什么是两个ASL之和
数据结构·算法
样例过了就是过了14 小时前
LeetCode热题100 最小栈
数据结构·c++·算法·leetcode
计算机安禾14 小时前
【数据结构与算法】第18篇:数组的压缩存储:对称矩阵、三角矩阵与稀疏矩阵
c语言·开发语言·数据结构·c++·线性代数·算法·矩阵