给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
树中节点数目在范围 [0, 2000] 内
-100 <= Node.val <= 100
思路:
层次遍历该树,将节点按层次保留下来,然后将层数为奇数的节点值的倒序一下
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* 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().
*/
//可以选择层次遍历后,将奇数层的数据反转即可
int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
*returnSize = 0;
if(root == NULL)
return NULL;
*returnColumnSizes = malloc(sizeof(int) * 2000);
int** res = (int**)malloc(sizeof(int*) * 2000);
struct TreeNode *arr[2000];
arr[0] = root;
int head = 0, tail = 1, last;
//层次遍历并将节点的值记录下来
while(head != tail){
last = tail;
int col_size = 0;
res[*returnSize] = malloc(sizeof(int) * (tail - head));
while(head < last){
res[*returnSize][col_size++] = arr[head]->val;
if(arr[head]->left)
arr[tail++] = arr[head]->left;
if(arr[head]->right)
arr[tail++] = arr[head]->right;
head++;
}
(*returnColumnSizes)[*returnSize] = col_size;
(*returnSize)++;
}
//将层数为奇数的节点值倒序
for(int i = 0; i < *returnSize ;i++){
if(i % 2 == 1){
for(int j = 0; j < (*returnColumnSizes)[i] / 2; j++){
last = res[i][j];
res[i][j] = res[i][(*returnColumnSizes)[i] - j - 1];
res[i][(*returnColumnSizes)[i] - j - 1] = last;
}
}
}
return res;
}