特定深度节点链表

题目链接:力扣(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;
}
相关推荐
aloha_7896 小时前
力扣hot100做题整理91-100
数据结构·算法·leetcode
Tiny番茄6 小时前
31.下一个排列
数据结构·python·算法·leetcode
挂科是不可能出现的6 小时前
最长连续序列
数据结构·c++·算法
_Aaron___6 小时前
List.subList() 返回值为什么不能强转成 ArrayList
数据结构·windows·list
码农多耕地呗8 小时前
力扣146.LRU缓存(哈希表缓存.映射+双向链表数据结构手搓.维护使用状况顺序)(java)
数据结构·leetcode·缓存
晚枫~8 小时前
数据结构基石:从线性表到树形世界的探索
数据结构
hadage2339 小时前
--- 数据结构 AVL树 ---
数据结构·算法
liu****9 小时前
8.list的使用
数据结构·c++·算法·list
立志成为大牛的小牛9 小时前
数据结构——二十六、邻接表(王道408)
开发语言·数据结构·c++·学习·程序人生
学编程就要猛11 小时前
数据结构初阶:时间和空间复杂度
数据结构