求c语言给定一颗二叉树,借助队列实现层次遍历二叉树的代码
时间: 2023-11-18 12:06:23 浏览: 110
好的,下面是基于队列实现层次遍历二叉树的 C 代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 定义队列节点结构体
typedef struct QueueNode {
TreeNode* data;
struct QueueNode* next;
} QueueNode;
// 定义队列结构体
typedef struct Queue {
QueueNode* front;
QueueNode* rear;
} Queue;
// 初始化队列
void initQueue(Queue* queue) {
queue->front = NULL;
queue->rear = NULL;
}
// 判断队列是否为空
int isQueueEmpty(Queue* queue) {
return queue->front == NULL;
}
// 入队
void enQueue(Queue* queue, TreeNode* data) {
QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
newNode->data = data;
newNode->next = NULL;
if (isQueueEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
// 出队
TreeNode* deQueue(Queue* queue) {
if (isQueueEmpty(queue)) {
return NULL;
}
TreeNode* data = queue->front->data;
QueueNode* temp = queue->front;
queue->front = queue->front->next;
free(temp);
return data;
}
// 层次遍历二叉树
int** levelOrder(TreeNode* root, int* returnSize, int** returnColumnSizes) {
if (!root) {
*returnSize = 0;
return NULL;
}
Queue queue;
initQueue(&queue); // 初始化队列
enQueue(&queue, root); // 将根节点加入队列
int** res = (int**)malloc(sizeof(int*) * 1000); // 二维数组存储遍历结果,1000 是数组的最大行数
*returnColumnSizes = (int*)malloc(sizeof(int) * 1000); // 存储每行的元素个数
int row = 0; // 当前行数
while (!isQueueEmpty(&queue)) {
int size = queueSize(&queue); // 当前队列大小
res[row] = (int*)malloc(sizeof(int) * size); // 初始化遍历结果的当前行
(*returnColumnSizes)[row] = size; // 初始化当前行的元素个数
for (int i = 0; i < size; i++) {
TreeNode* node = deQueue(&queue); // 出队一个节点
res[row][i] = node->val; // 将当前节点的值加入遍历结果中
if (node->left) {
enQueue(&queue, node->left); // 将当前节点的左子节点入队
}
if (node->right) {
enQueue(&queue, node->right); // 将当前节点的右子节点入队
}
}
row++; // 移动到下一行
}
*returnSize = row; // 最终遍历结果的行数
return res;
}
// 测试代码
int main() {
// 构造一颗二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 3;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 9;
root->left->left = NULL;
root->left->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 20;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 15;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
root->right->right->left = NULL;
root->right->right->right = NULL;
int returnSize;
int* returnColumnSizes;
int** res = levelOrder(root, &returnSize, &returnColumnSizes);
for (int i = 0; i < returnSize; i++) {
for (int j = 0; j < returnColumnSizes[i]; j++) {
printf("%d ", res[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果为:
```
3
9 20
15 7
```
希望能够帮到您!
阅读全文