二叉树的锯齿形层次遍历

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

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
   

返回锯齿形层次遍历如下:

[
[3],
[20,9],
[15,7]
]

(LeetCode)[https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal]


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
#define N 200

typedef struct tagNode {
    struct TreeNode *data[N];
    int size;
} Stack;

void reverse(int *arr, int size)
{
    int temp;
    for (int i = 0, j = size - 1; i < j; i++, j--) {
        temp = *(arr + i);
        *(arr + i) = *(arr + j);
        *(arr + j) = temp;
    }
}

void swapPointer(Stack **ppS1, Stack **ppS2)
{
    Stack *pTemp;
    pTemp = *ppS1;
    *ppS1 = *ppS2;
    *ppS2 = pTemp;
}

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
Stack g_stack1, g_stack2;
int g_dataNum = 0;
int g_dataArr[N];
int **zigzagLevelOrder(struct TreeNode *root, int *returnSize, int **returnColumnSizes)
{
    if (!root) {
        *returnSize = 0;
        return NULL;
    }
    // 内存申请
    *returnColumnSizes = (int *)malloc(N * sizeof(int));
    int **res = (int **)malloc(N * sizeof(int *));
    for (int i = 0; i < N; ++i) {
        *(res + i) = (int *)malloc(N * sizeof(int));
    }

    int arrArrSize = 0;
    Stack *pstack1 = &g_stack1, *pstack2 = &g_stack2;
    g_stack1.data[0] = root;
    g_stack1.size = 1;
    g_stack2.data[0];
    g_stack2.size = 0;

    struct TreeNode *node;
    int idx = 0;
    int flag = 0;
    while (pstack1->size || pstack2->size) {
        // printf("pstack1->size %d\n", pstack1->size);
        idx = 0;
        while (idx < pstack1->size) {
            node = pstack1->data[idx];
            g_dataArr[g_dataNum++] = node->val;
            if (node->left) {
                pstack2->data[pstack2->size++] = node->left;
            }
            if (node->right) {
                pstack2->data[pstack2->size++] = node->right;
            }
            idx++;
        }
        // 翻转 & 拷贝数据
        if (flag) {
            reverse(g_dataArr, g_dataNum);
            flag = 0;
        } else {
            flag = 1;
        }
        memcpy(*(res + arrArrSize), g_dataArr, g_dataNum * sizeof(int));
        *((*returnColumnSizes) + arrArrSize) = g_dataNum;
        arrArrSize++;
        g_dataNum = 0;
        // 交换堆栈指针, 便于重新出栈
        pstack1->size = 0;
        swapPointer(&pstack1, &pstack2);
    }

    *returnSize = arrArrSize;
    return res;
}

你可能感兴趣的:(leetcode)