102. 二叉树的层序遍历
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]。
BFS返回数组是一维数组,而分层遍历返回的是二维数组
因此,需要计算每层的结点数
#define MAXSIZE 1000
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
int **res = (int **)calloc(MAXSIZE, sizeof(int *));
(*returnColumnSizes) = (int *)calloc(MAXSIZE, sizeof(int));
(*returnSize) = 0;
struct TreeNode *queue[10000];
int Outsize = 0;
int Insize = 0;
if(root == NULL) {return NULL;}
queue[Insize++] = root;
int size = Insize - Outsize;
// BFS
while(size > 0) {
res[*returnSize] = (int *)calloc(size, sizeof(int));
(*returnColumnSizes)[*returnSize] = size;
// 每一层的动作
for(int i = 0; i < size; i++) {
if(queue[Outsize]->left != NULL) {
queue[Insize++] = queue[Outsize]->left;
}
if(queue[Outsize]->right != NULL) {
queue[Insize++] = queue[Outsize]->right;
}
res[*returnSize][i] = queue[Outsize]->val;
Outsize++;
}
// 进入下一层之前的动作
(*returnSize)++;
size = Insize - Outsize;
}
return res;
}