这道题和上道题是一样的,不同在于赋值需要一个行数奇偶判断部分。
具体分析参考剑指offer32.
时间和内存消耗以及源代码如下:
/**
* 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** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
*returnSize = 0;
if (root == NULL)
{
return NULL;
}
int** reverse;
reverse = (int**) malloc (2000*sizeof(int*));
*returnColumnSizes = (int*) malloc (2000*sizeof(int));
struct TreeNode* temp[2000];
struct TreeNode* ptemp;
ptemp = (struct TreeNode*) malloc (sizeof(struct TreeNode));
int start = 0;
int end = 0;
temp[end] = root;
end++;
int counts = 1;
while (start < end)
{
int size = end - start;
reverse[*returnSize] = (int*) malloc (size * sizeof(int));
counts = 0;
for (int i = 0; i < size; i++)
{
ptemp = temp[start];
if (ptemp->left)
{
temp[end] = ptemp->left;
end++;
}
if (ptemp->right)
{
temp[end] = ptemp->right;
end++;
}
//判断部分
if ((*returnSize)%2)
{
reverse[*returnSize][size-1-i] = ptemp->val;
}
else
{
reverse[*returnSize][i] = ptemp->val;
}
start++;
}
(*returnColumnSizes)[(*returnSize)] = size;
(*returnSize)++;
}
return reverse;
}