一、题目
此题和剑指 Offer 32 - I为同类型的题目。可以先看前面的题目再来看这一题
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
二、思路
层次遍历,与上一个题目不同的是,这次要求输出的为二维数组,思路和上一个题目是一样的。这里采用两个辅助队列,第一个队列的元素的孩子输出到第二个队列,当第一个队列输出完毕后,开始输出第二个队列的元素,并且孩子全部输出到第一个队列,如此循环直到两个队列全部输出完成。
三、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 QueenFront1=0,QueenSize1 = 0;
int QueenFront2=0,QueenSize2 = 0;
int retSize = calcTreeSize(root);
int * countColSize=(int*) malloc(retSize*sizeof(int));
struct TreeNode *tree1 = (struct TreeNode*)malloc(retSize*sizeof(struct TreeNode));//队列1
struct TreeNode *tree2 = (struct TreeNode*)malloc(retSize*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;
}
}
*returnSize = count;
*returnColumnSizes = countColSize;
return ans;
}