leetcode做题笔记103. 二叉树的锯齿形层序遍历

给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

思路一:BFS

cpp 复制代码
#define N 2000

int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {
    *returnSize = 0;
    if (root == NULL) {
        return NULL;
    }
    int** ans = malloc(sizeof(int*) * N);
    *returnColumnSizes = malloc(sizeof(int) * N);
    struct TreeNode* nodeQueue[N];
    int left = 0, right = 0;
    nodeQueue[right++] = root;
    bool isOrderLeft = true;

    while (left < right) {
        int levelList[N * 2];
        int front = N, rear = N;
        int size = right - left;
        for (int i = 0; i < size; ++i) {
            struct TreeNode* node = nodeQueue[left++];
            if (isOrderLeft) {
                levelList[rear++] = node->val;
            } else {
                levelList[--front] = node->val;
            }
            if (node->left) {
                nodeQueue[right++] = node->left;
            }
            if (node->right) {
                nodeQueue[right++] = node->right;
            }
        }
        int* tmp = malloc(sizeof(int) * (rear - front));
        for (int i = 0; i < rear - front; i++) {
            tmp[i] = levelList[i + front];
        }
        ans[*returnSize] = tmp;
        (*returnColumnSizes)[*returnSize] = rear - front;
        (*returnSize)++;
        isOrderLeft = !isOrderLeft;
    }
    return ans;
}

分析:

本题与上题相似,直接使用广度优先搜索将每层数放入数组再输出即可,注意 (*returnColumnSizes)\*returnSize = rear - front;

总结:

本题考察广度优先搜索算法,将每层按左向右再右向左的顺序放入数组再输出即可

相关推荐
Xin7707 小时前
LeetCode 23.合并 K 个升序链表(分治递归)
leetcode
Nil20810 小时前
leetcode 105从前序和中序遍历序列构造二叉树
算法·leetcode·职场和发展
一直C10 小时前
【数据结构】哈希表+算法复杂度与经典排序查找(C语言)
java·linux·开发语言·数据结构·算法·ubuntu·散列表
淡海水10 小时前
04-02-哈希-Dictionary-TKey-TValue-上-核心数据结构
数据结构·算法·c#·哈希算法·编译·字典·dictionary
Nil20810 小时前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
cz071011 小时前
hot100_搜索二维矩阵 II
算法·leetcode
疯狂打码的少年11 小时前
【数据结构】板块总结 + 下期预告(数据库技术)
数据结构·笔记·算法
郝学胜-神的一滴11 小时前
Effective Python 条款 1:确认你正在使用的 Python 版本
开发语言·数据结构·python·程序人生·算法
圣保罗的大教堂13 小时前
leetcode 3718. 缺失的最小倍数 简单
leetcode
dtq042413 小时前
数据结构 - 线性表 - 单链表
数据结构