leetcode 第102题 c语言实现
时间: 2023-03-25 14:02:19 浏览: 180
可以使用队列来实现二叉树的层序遍历,具体实现可以参考以下代码:
```
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int** levelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
if (root == NULL) {
*returnSize = ;
return NULL;
}
int** res = (int**)malloc(sizeof(int*) * 100);
*returnColumnSizes = (int*)malloc(sizeof(int) * 100);
int front = , rear = ;
struct TreeNode* queue[100];
queue[rear++] = root;
while (front < rear) {
int size = rear - front;
(*returnColumnSizes)[*returnSize] = size;
res[*returnSize] = (int*)malloc(sizeof(int) * size);
for (int i = ; i < size; i++) {
struct TreeNode* node = queue[front++];
res[*returnSize][i] = node->val;
if (node->left) {
queue[rear++] = node->left;
}
if (node->right) {
queue[rear++] = node->right;
}
}
(*returnSize)++;
}
return res;
}
```
阅读全文