题目:
从上到下打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印一行
思路:
这个题和前面的题目类似,唯一一个变得复杂的就是要把值放入二维数组中,同样为了从上到下的打印这些节点值,我们也可以用一个队列来保存将要打印的节点。二叉树中的遍历无非就是先向左还是先向右之分,为了能分行打印,所以我们就要确定每一层的节点数,节点数又如何确定呢,其实利用压栈结束后的rear和head之差就可以算出来,所以我们每一次循环之前我们要设置一个prerear来保存上一次压栈的rear,利用prerear-head我们就可以知道这层有几个结点,就可以确定弹多少次栈,弹一次入1次数组,再把这个结点的子节点入栈。
代码实现:
/**
* 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){
if(!root){
*returnSize=0;
*returnColumnSizes=NULL;
return NULL;
}
*returnSize=0;
int** res=(int**)malloc(sizeof(int*)*10001);
*returnColumnSizes=(int*)malloc(sizeof(int)*10001);
struct TreeNode** queue=(struct TreeNode**)malloc(sizeof(struct TreeNode*)*10001);
int head=0,rear=0;
queue[rear++]=root;
while(head<rear){
int prerear=rear;
res[*returnSize]=(int*)malloc(sizeof(int)*(prerear-head));
(*returnColumnSizes)[*returnSize]=prerear-head;
int index=0;
for(;head<prerear;head++){
struct TreeNode* tmp=queue[head];
res[*returnSize][index++]=tmp->val;
if(tmp->left){
queue[rear++]=tmp->left;
}
if(tmp->right){
queue[rear++]=tmp->right;
}
}
(*returnSize)++;
}
return res;
}
分行之字形打印
之字形打印的特点就是多了一个奇数偶数判断,*returnsize来确认就好了。
/**
* 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){
/* 特判 */
if (!root) {
*returnSize = 0;
*returnColumnSizes = NULL;
return NULL;
}
/* 返回数组的行数 */
*returnSize = 0;
/* 返回数组 */
int** res = (int**)malloc(sizeof(int*) * 10001);
/* 返回数组中每一行的列数 */
*returnColumnSizes = (int*)malloc(sizeof(int) * 10001);
/* 队列 */
struct TreeNode** queue = (struct TreeNode**)malloc(sizeof(struct TreeNode*) * 10001);
int head = 0, rear = 0;
queue[rear++] = root;
/* 遍历二叉树 */
while (head < rear) {
/* 记录当前的rear */
int preRear = rear;
/* 当前行的列数 */
res[*returnSize] = (int*)malloc(sizeof(int) * (preRear - head));
(*returnColumnSizes)[*returnSize] = preRear - head;
int index;
if (*returnSize % 2 == 0) {
index = 0;
} else {
index = preRear - head - 1;
}
/* 遍历当前行 */
for (; head < preRear; head++) {
if (*returnSize % 2 == 0) {
res[*returnSize][index++] = queue[head]->val;
} else {
res[*returnSize][index--] = queue[head]->val;
}
/* 添加当前节点的左右孩子 */
if (queue[head]->left) {
queue[rear++] = queue[head]->left;
}
if (queue[head]->right) {
queue[rear++] = queue[head]->right;
}
}
/* 遍历层数加一 */
(*returnSize)++;
}
return res;
}