#define MaxSize 2000
int TreeDepth(struct TreeNode *p)
{
int depth = 0;
int LD, RD;
if (p == NULL)
return 0;
else
{
LD = TreeDepth(p->left);
RD = TreeDepth(p->right);
return (LD >= RD ? LD : RD) + 1;
}
}
int **Print(struct TreeNode *pRoot, int *returnSize, int **returnColumnSizes)
{
struct TreeNode *que[MaxSize];
struct TreeNode *temp;
int depth = TreeDepth(pRoot);
//计算深度
int **arr;
arr = (int **)malloc(sizeof(int *) * depth);
for (int i = 0; i < depth; i++)
arr[i] = (int *)malloc(sizeof(int) * MaxSize);
//层序遍历
//用队列来记录节点,二叉树从左向右进入队列,先进先出
//用col来记录每一层需要输出的列数
int front = 0, rear = 0;
int row = 0, col[depth];
memset(col, 0, sizeof(col));
if (pRoot)
{
que[++rear] = pRoot;
col[row] = 1;
while (rear != front)
{
//输出是下标为偶数行顺序进入数组,奇数行逆序进入数组
if (row % 2 == 0)
{
for (int i = 0; i < col[row]; i++)
{
temp = que[++front];
arr[row][i] = temp->val;
if (temp->left)
{
que[++rear] = temp->left;
col[row + 1]++;
}
if (temp->right)
{
que[++rear] = temp->right;
col[row + 1]++;
}
}
row++;
}
if (row % 2 == 1 && rear!=front)
{
for (int i = col[row] - 1; i >= 0; i--)
{
temp = que[++front];
arr[row][i] = temp->val;
if (temp->left)
{
que[++rear] = temp->left;
col[row + 1]++;
}
if (temp->right)
{
que[++rear] = temp->right;
col[row + 1]++;
}
}
row++;
}
}
}
*returnSize = depth;
*returnColumnSizes =col;
return arr;
}