环境:VS2019 C语言
问题:根据传入函数的参数和返回值输出二维数组内的所有元素的方法。
程序目的:实现二叉树的层序遍历
函数如下:
int** LevelOrder(struct TreeNode *root,int *returnSize,int** returnColumnSizes){
*returnSize = 0;
if (root == NULL) {
return NULL;
}
int** res =(int**)malloc(sizeof(int*) * 1000);
*returnColumnSizes =(int*)malloc(sizeof(int)*1000);
if (!res || !*returnColumnSizes)
return NULL;
struct TreeNode* queue[1000];
int front = -1, rear = -1;
queue[++rear] = root;
while (rear != front) {
(*returnColumnSizes)[*returnSize] = rear - front;
res[*returnSize] =(int*)malloc(sizeof(int)*(rear-front));
if (res[*returnSize] == NULL) return NULL;
for (int i = 0, j = front + 1; i < rear - front;i++,j++){
res[*returnSize][i] = queue[j]->val;
}
(*returnSize)++;
int tmp = rear;
for (int i = front + 1; i <= tmp;i++) {
if (queue[i]->left) {
queue[++rear] = queue[i]->left;
}
if (queue[i]->right) {
queue[++rear] = queue[i]->right;
}
}
front = tmp;
}
return res;
}
#include<malloc.h>
#include<stdio.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
}BiTnode;
void CreateBiTree(BiTnode** root) {
if (*root == NULL) return;
int value = -1;
scanf_s("%d", &value);
if (value == -1) {
*root = NULL;
}
else {
*root =(BiTnode*)malloc(sizeof(BiTnode));
if (*root == NULL) return;
(*root)->val = value;
printf("左子树:\n");
CreateBiTree(&(*root)->left);
printf("右子树:\n");
CreateBiTree(&(*root)->right);
}
}
int** LevelOrder(struct TreeNode *root,int *returnSize,int** returnColumnSizes){
*returnSize = 0;
if (root == NULL) {
return NULL;
}
/***
*returnSize返回输出的数目
**returnColumnSizes每层的结点数
***/
int** res =(int**)malloc(sizeof(int*) * 1000);
*returnColumnSizes =(int*)malloc(sizeof(int)*1000);
if (!res || !*returnColumnSizes)
return NULL;
struct TreeNode* queue[1000];
int front = -1, rear = -1;
queue[++rear] = root;
while (rear != front) {
/***
当前层的结点数
***/
(*returnColumnSizes)[*returnSize] = rear - front;
res[*returnSize] =(int*)malloc(sizeof(int)*(rear-front));
if (res[*returnSize] == NULL) return NULL;
for (int i = 0, j = front + 1; i < rear - front;i++,j++){
/***
把这一层的节点值放入结果数组中
***/
res[*returnSize][i] = queue[j]->val;
}
(*returnSize)++;
int tmp = rear;
for (int i = front + 1; i <= tmp;i++) {
if (queue[i]->left) {
queue[++rear] = queue[i]->left;
}
if (queue[i]->right) {
queue[++rear] = queue[i]->right;
}
}
front = tmp;
}
return res;
}
int main() {
BiTnode *root;
int returnSize;
int* returnColumnSize;
int** res;
CreateBiTree(&root);
res=LevelOrder(root, &returnSize, &returnColumnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", res[returnSize]);
}
return 0;
}