一、题目
此题和剑指 Offer 32 - I和剑指 Offer 32 - II为同类型的题目。可以先看前面的题目再来看这一题
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[20,9],
[15,7]
]
二、思路
大概思路查看上面提到的文章,在剑指 Offer 32 - II的答案上,将奇数行元素翻转即可
三、C语言解法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//返回二叉树节点数
int calcTreeSize(struct TreeNode* root)
{
if(root == NULL)
{
return 0;
}
return 1 + calcTreeSize(root->left) + calcTreeSize(root->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){
if(root == NULL){*returnSize =0;return NULL;}
int count = 0,countCol=0;
int * countColSize=(int*) malloc(1010*sizeof(int));
int QueenFront1=0,QueenSize1 = 0;
int QueenFront2=0,QueenSize2 = 0;
int retSize = calcTreeSize(root);
struct TreeNode *tree1 = (struct TreeNode*)malloc((retSize+1)*sizeof(struct TreeNode));//队列1
struct TreeNode *tree2 = (struct TreeNode*)malloc((retSize+1)*sizeof(struct TreeNode));//队列2
int **ans = (int**) malloc(retSize*sizeof(int*));//行数组指针
int *ansrow = (int*) malloc(retSize*retSize*sizeof(int));//每一行的数组指针
for (int i = 0; i < retSize; i++) {
ans[i] = ansrow + retSize*i;
}
tree1[QueenFront1]= *root;
QueenSize1++;
while(QueenFront1 != QueenSize1||QueenFront2 != QueenSize2){
while(QueenFront1 != QueenSize1) {
ans[count][countCol]=tree1[QueenFront1].val;
// printf("%d",ansrow[countCol]);
countCol++;
if(tree1[QueenFront1].left!=NULL)tree2[QueenSize2++] = *tree1[QueenFront1].left;
if(tree1[QueenFront1].right!=NULL)tree2[QueenSize2++] = *tree1[QueenFront1].right;
QueenFront1++;
}
if(countCol!=0){
countColSize[count]=countCol;
count++;
countCol = 0;
}
while(QueenFront2 != QueenSize2) {
ans[count][countCol]=tree2[QueenFront2].val;
countCol++;
if(tree2[QueenFront2].left!=NULL)tree1[QueenSize1++] = *tree2[QueenFront2].left;
if(tree2[QueenFront2].right!=NULL)tree1[QueenSize1++] = *tree2[QueenFront2].right;
QueenFront2++;
}
if(countCol!=0){
countColSize[count]=countCol;
count++;
countCol = 0;
}
}
int left=0,right=0,temp=0;;
for(int i=1;i<count;i+=2){
left = 0;
right = countColSize[i]-1;
while(left<right){
temp = ans[i][right];
ans[i][right] = ans[i][left];
ans[i][left] = temp;
left++;
right--;
}
}
*returnSize = count;
*returnColumnSizes = countColSize;
return ans;
}