leetcode 103 二叉树的锯齿形层次遍历 C语言实现

题目

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

例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]

代码

int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
    *returnSize = 0;
    if (root == NULL) return 0;
    #define MAX 1000000
    int **arr = (int **)malloc(sizeof(int *) * MAX);
    (*returnColumnSizes) = (int *)malloc(sizeof(int) * MAX);
    struct TreeNode *q[MAX], *p;
    int front = 0, rear = -1, last = 0;
    q[++rear] = root;
    int num[MAX], k = 0;
    while (front <= rear) {
        p = q[front++];
        num[k++] = p->val;
        if (p->left) q[++rear] = p->left;
        if (p->right) q[++rear] = p->right;
        if (last == front - 1) {
            int j = 0;
            arr[*returnSize] = (int *)malloc(sizeof(int) * k);
            if ((*returnSize) % 2 == 0) {
                for (int i = 0; i < k; i++) 
                    arr[*returnSize][j++] = num[i];
            } else {
                for (int i = k - 1; i >= 0; i--) 
                    arr[*returnSize][j++] = num[i];
            }
            (*returnColumnSizes)[*returnSize] = k;
            (*returnSize)++;
            k = 0;
            last = rear;
        }
    }
    return arr;
}

你可能感兴趣的:(LeetCode)