请用C语言实现二叉树层序排列
时间: 2023-11-21 15:04:14 浏览: 60
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树结点结构体
typedef struct node {
int val;
struct node* left;
struct node* right;
} Node;
// 定义队列结构体
typedef struct queue {
Node* data;
struct queue* next;
} Queue;
// 初始化队列
Queue* initQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->data = NULL;
q->next = NULL;
return q;
}
// 入队操作
void enqueue(Queue* q, Node* data) {
Queue* new_node = (Queue*)malloc(sizeof(Queue));
new_node->data = data;
new_node->next = NULL;
while (q->next != NULL) {
q = q->next;
}
q->next = new_node;
}
// 出队操作
Node* dequeue(Queue* q) {
if (q->next == NULL) {
return NULL;
}
Queue* temp = q->next;
q->next = temp->next;
Node* data = temp->data;
free(temp);
return data;
}
// 创建二叉树
Node* createTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
Node* root = (Node*)malloc(sizeof(Node));
root->val = val;
root->left = createTree();
root->right = createTree();
return root;
}
// 层序遍历
void levelOrder(Node* root) {
if (root == NULL) {
return;
}
Queue* q = initQueue();
enqueue(q, root);
while (q->next != NULL) {
Node* node = dequeue(q);
printf("%d ", node->val);
if (node->left != NULL) {
enqueue(q, node->left);
}
if (node->right != NULL) {
enqueue(q, node->right);
}
}
}
int main() {
Node* root = createTree();
levelOrder(root);
return 0;
}
阅读全文