难度:mid
题目描述
示例
解法1:层序遍历
写这个花了不少时间,不是很清楚c语言中二维数组的定义方式。现在总结如下:
首先要定义一个二维数组int** res,res是一个指针的指针。他的第一层指针指向一个二维数组,第二层指针指向一个一维数组。
要构建一个完整的二维数组,就得先malloc一个一维数组,再用二维数组的第二层指针指过去即可。
举个栗子
int **res = (int**)malloc(sizeof(int*)*2010); // res是一个二维数组
int i;
for(i = 0; i < 2010; i++){
int* leval = (int*)malloc(sizeof(int)*2010);
res[i] = leval;
}
下面是本题的完整代码,一个简单的层序遍历
/**
* 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) {
// *returnSize表示有多少层, **returnColumnSizes表示每一层有多少个结点
if(root == NULL){
*returnSize = 0;
return NULL;
}
int **res = (int**)malloc(sizeof(int*)*2010); // res是一个二维数组
*returnColumnSizes = malloc(sizeof(int) * 2010);
// 数组模拟队列
struct TreeNode* queue[2010];
int i, row=0, qsize=1, qsize_next, head=0, tail=0, k=0;
struct TreeNode* p;
queue[0] = root;
while(head <= tail){
int* leval = (int*)malloc(sizeof(int) * qsize);
int col = 0;
for(i = 0; i < qsize; i ++){
p = queue[head++]; // 队头元素出队
leval[col++] = p->val;
if(p->left){
queue[++tail] = p->left;
qsize_next ++;
}
if(p->right){
queue[++tail] = p->right;
qsize_next ++;
}
}
res[row++] = leval;
(*returnColumnSizes)[k++] = col;
qsize = qsize_next;
qsize_next = 0;
}
*returnSize = k;
return res;
}
关于malloc函数
int *arr;
int size = 5; // 使用malloc分配整数数组内存
arr = (int *)malloc(size * sizeof(int));