c语言按层次遍历二叉树代码
时间: 2023-06-06 07:07:24 浏览: 83
这个问题可以回答。以下是C语言按层次遍历二叉树的代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 100 // 定义队列的最大长度
// 定义二叉树的节点结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 定义队列结构体
typedef struct Queue {
int front, rear;
TreeNode* arr[MAX_QUEUE_SIZE];
} Queue;
// 初始化队列
Queue* createQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->front = -1;
q->rear = -1;
return q;
}
// 判断队列是否为空
int isQueueEmpty(Queue* q) {
return (q->front == -1 && q->rear == -1);
}
// 入队
void enqueue(Queue* q, TreeNode* node) {
if (q->rear == MAX_QUEUE_SIZE - 1) {
printf("Queue overflow");
return;
}
// 如果队列为空,需要更新front
if (q->front == -1) {
q->front = 0;
}
q->rear++;
q->arr[q->rear] = node;
}
// 出队
TreeNode* dequeue(Queue* q) {
if (isQueueEmpty(q)) {
printf("Queue underflow");
exit(1);
}
TreeNode* node = q->arr[q->front];
if (q->front == q->rear) {
q->front = -1;
q->rear = -1;
} else {
q->front++;
}
return node;
}
// 层次遍历二叉树
void levelOrderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
Queue* q = createQueue();
enqueue(q, root);
while (!isQueueEmpty(q)) {
TreeNode* node = dequeue(q);
printf("%d ", node->val);
if (node->left != NULL) {
enqueue(q, node->left);
}
if (node->right != NULL) {
enqueue(q, node->right);
}
}
}
// 创建二叉树
TreeNode* createTree() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
return root;
}
int main() {
TreeNode* root = createTree();
levelOrderTraversal(root);
return 0;
}
```
阅读全文