用c语言写一个用层序遍历输入的二叉树
时间: 2023-03-26 17:03:34 浏览: 113
二叉树遍历_C语言_
5星 · 资源好评率100%
可以使用队列来实现二叉树的层序遍历。具体步骤如下:
1. 定义一个队列,将根节点入队。
2. 当队列不为空时,取出队首元素,输出该节点的值,并将其左右子节点入队。
3. 重复步骤2,直到队列为空。
以下是示例代码:
```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;
void initQueue(Queue *q) {
q->front = q->rear = NULL;
}
int isEmpty(Queue *q) {
return q->front == NULL;
}
void enqueue(Queue *q, TreeNode *node) {
QueueNode *newNode = (QueueNode *)malloc(sizeof(QueueNode));
newNode->node = node;
newNode->next = NULL;
if (isEmpty(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
TreeNode *dequeue(Queue *q) {
if (isEmpty(q)) {
return NULL;
}
TreeNode *node = q->front->node;
QueueNode *temp = q->front;
q->front = q->front->next;
free(temp);
if (q->front == NULL) {
q->rear = NULL;
}
return node;
}
TreeNode *buildTree(int *arr, int size, int index) {
if (index >= size || arr[index] == -1) {
return NULL;
}
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = arr[index];
root->left = buildTree(arr, size, 2 * index + 1);
root->right = buildTree(arr, size, 2 * index + 2);
return root;
}
void levelOrder(TreeNode *root) {
if (root == NULL) {
return;
}
Queue q;
initQueue(&q);
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() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1};
int size = sizeof(arr) / sizeof(arr[]);
TreeNode *root = buildTree(arr, size, );
levelOrder(root);
return ;
}
```
阅读全文