# 题解 | #按之字形顺序打印二叉树#

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

```/**
* struct TreeNode {
*  int val;
*  struct TreeNode *left;
*  struct TreeNode *right;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return int整型二维数组
* @return int* returnSize 返回数组行数
* @return int** returnColumnSizes 返回数组列数
*/
int** Print(struct TreeNode* pRoot, int* returnSize, int** returnColumnSizes ) {
// write code here
*returnColumnSizes = (int*)malloc(sizeof(int) * 1500);
int** res = (int**)malloc(sizeof(int*) * 1500);
int gidx = 0;
bool zx = true;
//memset(res, NULL, 11);
struct TreeNode* que1[1501] = { NULL };
int idx1 = 0;
struct TreeNode* que2[1501] = { NULL };
int idx2 = 0;
struct TreeNode* move = NULL;

if (pRoot != NULL) {
//根节点进队列
que1[idx1++] = pRoot;
move = que1[0];
} else {
return NULL;
}

while (move != NULL) {
//判断从哪个队列进数组，正序还是反序进
if ((gidx + 1) % 2 == 1) {
res[gidx] = (int*)malloc(sizeof(int) * idx1);
zx = true;
} else {
res[gidx] = (int*)malloc(sizeof(int) * idx2);
zx = false;
}
if (zx) {
for (int i = 0; i < idx1; i++) {
//出队列
res[gidx][i] = que1[i]->val;
//子节点进另一个队列
if (que1[i]->left != NULL) que2[idx2++] = que1[i]->left;
if (que1[i]->right != NULL) que2[idx2++] = que1[i]->right;
}
(*returnColumnSizes)[gidx] = idx1;
idx1 = 0;
move = que2[0];
} else {
for (int i = 0; i < idx2; i++) {
//出队列
res[gidx][i] = que2[idx2 - 1 - i]->val;
//子节点进另一个队列
if (que2[i]->left != NULL) que1[idx1++] = que2[i]->left;
if (que2[i]->right != NULL) que1[idx1++] = que2[i]->right;
}
(*returnColumnSizes)[gidx] = idx2;
idx2 = 0;
move = que1[0];
}
//free(res[gidx]);
gidx++;
if (idx1 == 0 && idx2 == 0) break;
}
*returnSize = gidx;
return res;
}
```