二叉树层序遍历c语言实现
时间: 2023-10-13 09:06:42 浏览: 123
c语言实现二叉树的遍历
5星 · 资源好评率100%
二叉树层序遍历是一种广度优先搜索(BFS)算法,可以使用队列来实现。具体步骤如下:
1. 首先将根节点入队列。
2. 当队列不为空时,重复以下步骤:
- 从队列中取出一个节点,输出该节点的值。
- 如果该节点有左子节点,将左子节点入队列。
- 如果该节点有右子节点,将右子节点入队列。
以下是二叉树层序遍历的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
typedef struct QueueNode {
TreeNode* node;
struct QueueNode* next;
} QueueNode;
typedef struct Queue {
QueueNode* front;
QueueNode* rear;
} Queue;
Queue* createQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->front = q->rear = NULL;
return q;
}
void enqueue(Queue* q, TreeNode* node) {
QueueNode* qnode = (QueueNode*)malloc(sizeof(QueueNode));
qnode->node = node;
qnode->next = NULL;
if (q->rear == NULL) {
q->front = q->rear = qnode;
} else {
q->rear->next = qnode;
q->rear = qnode;
}
}
TreeNode* dequeue(Queue* q) {
if (q->front == NULL) {
return NULL;
}
TreeNode* node = q->front->node;
QueueNode* temp = q->front;
q->front = q->front->next;
if (q->front == NULL) {
q->rear = NULL;
}
free(temp);
return node;
}
int isEmpty(Queue* q) {
return q->front == NULL;
}
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
Queue* q = createQueue();
enqueue(q, root);
while (!isEmpty(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);
}
}
}
int main() {
/*
1
/ \
2 3
/ \ \
4 5 6
*/
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 6;
root->right->right->left = NULL;
root->right->right->right = NULL;
levelOrder(root); // output: 1 2 3 4 5 6
return 0;
}
```
阅读全文