题目链接:
求二叉树的层序遍历_牛客题霸_牛客网 (nowcoder.com)
题目简介:
描述
给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
该二叉树层序遍历的结果是
[
[3],
[9,20],
[15,7]]
提示:
0 <= 二叉树的结点数 <= 1500
题目解法:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*
*BM26 求二叉树的层序遍历
描述
给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
*/
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param root TreeNode类
* @return int整型二维数组
* @return int* returnSize 返回数组行数
* @return int** returnColumnSizes 返回数组列数
*/
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes ) {
// write code here
if(root == NULL)return NULL;
*returnSize = -1;
// **returnColumnSizes = 0; //BUG:指向地址0
int LayerNodeCnt;
struct TreeNode* node;
struct TreeNode** st1 = (struct TreeNode**)malloc(sizeof(struct TreeNode*)*100001);
struct TreeNode** st2 = (struct TreeNode**)malloc(sizeof(struct TreeNode*)*100001);
int** ret = (int**)malloc(sizeof(int*) * 100001);
*returnColumnSizes = (int*)malloc(sizeof(int)*100001);
// int ret[3][3] = {0};
int st1_i = -1, st2_i = -1, st2_i_Max;
st1[++st1_i] = root;
while(st1_i >= 0){
if(st1[st1_i] !=NULL){
while(st1_i >= 0){ //将当前层的元素压入st2
st2[++st2_i] = st1[st1_i--];
}
st2_i_Max = st2_i; //记录当前层的元素个数
LayerNodeCnt = 0;
while(st2_i >= 0){ //将当前层的子节点按顺序压入st1
node = st2[st2_i--];
LayerNodeCnt++; //当前层元素计数
if(node->right) {st1[++st1_i] = node->right; }
if(node->left) {st1[++st1_i] = node->left;}
}
st2_i = st2_i_Max;
while(st2_i >= 0){ //将使用完的当前层每隔一个元素+NULL压回st1
st1[++st1_i] = st2[st2_i--];
st1[++st1_i] = NULL;
}
(*returnSize)++; //更新层数
(*returnColumnSizes)[*returnSize] = LayerNodeCnt; //更新当前层数中元素个数
ret[*returnSize] = (int*)malloc(sizeof(int)*LayerNodeCnt);//为返回数组申请当前层数的元素存储空间
LayerNodeCnt = 0; //为了下面弹栈,需要在这里清0
}else{
st1_i--; //弹出NULL
ret[*returnSize][LayerNodeCnt++] = st1[st1_i--]->val; //将已使用的当前层数的元素弹出到ret
}
}
free(st1);
free(st2);
(*returnSize)++; //前面为了方便使用数组,计数是从0开始,退出函数需要变为从1开始,故++
return (int**)ret;
}
/**************************end******************************************/
int main ()
{
int returnSize = 0;
int* returnColumnSizes;
struct TreeNode n22 ={.val =7 , .left = NULL, .right = NULL};
struct TreeNode n21 ={.val =15 , .left = NULL, .right = NULL};
struct TreeNode n2 ={.val =20 , .left = &n21, .right = &n22};
struct TreeNode n1 ={.val =9 , .left = NULL, .right = NULL};
struct TreeNode root ={.val =3 , .left = &n1, .right = &n2};
// struct TreeNode n1 ={.val =2 , .left = NULL, .right = NULL};
// struct TreeNode root ={.val =1 , .left = &n1, .right = NULL};
int** ret = levelOrder(&root, &returnSize, &returnColumnSizes);
for(int i=0; i<returnSize; i++){
for(int j=0; j<*returnColumnSizes; j++)
printf("%d->", ret[i][j]);
}
return 0;
}