c语言用队列实现二叉树的层次遍历
时间: 2023-10-11 08:13:28 浏览: 124
数据结构:二叉树层次遍历算法解析及C语言实现
以下是C语言使用队列实现二叉树的层次遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结构体
typedef struct node {
int data;
struct node *left;
struct node *right;
} Node;
// 定义队列结构体
typedef struct queue {
Node *data;
struct queue *next;
} Queue;
// 全局变量,指向队列头和尾
Queue *front = NULL, *rear = NULL;
// 入队操作
void enqueue(Node *data) {
Queue *newNode = (Queue *) malloc(sizeof(Queue));
newNode->data = data;
newNode->next = NULL;
if (rear == NULL) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
}
// 出队操作
Node *dequeue() {
if (front == NULL) {
return NULL;
}
Node *data = front->data;
Queue *temp = front;
if (front == rear) {
front = rear = NULL;
} else {
front = front->next;
}
free(temp);
return data;
}
// 创建二叉树
Node *createTree() {
int data;
printf("请输入节点的值(-1表示空节点):");
scanf("%d", &data);
if (data == -1) {
return NULL;
}
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
node->left = createTree();
node->right = createTree();
return node;
}
// 层次遍历
void levelOrderTraversal(Node *root) {
if (root == NULL) {
return;
}
enqueue(root);
while (front != NULL) {
Node *node = dequeue();
printf("%d ", node->data);
if (node->left != NULL) {
enqueue(node->left);
}
if (node->right != NULL) {
enqueue(node->right);
}
}
}
int main() {
Node *root = createTree();
printf("层次遍历结果:");
levelOrderTraversal(root);
return 0;
}
```
阅读全文