C语言代码编程实现二叉树按层序输出
时间: 2023-12-10 21:49:11 浏览: 75
C语言实现二叉树
当然可以帮您解决关于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 head;
int tail;
TreeNode* node[MAX_QUEUE_SIZE];
} Queue;
Queue* createQueue() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->head = queue->tail = 0;
return queue;
}
int isEmpty(Queue* queue) {
return queue->head == queue->tail;
}
int isFull(Queue* queue) {
return (queue->tail + 1) % MAX_QUEUE_SIZE == queue->head;
}
void enqueue(Queue* queue, TreeNode* node) {
if (isFull(queue)) {
printf("Queue is full.\n");
return;
}
queue->node[queue->tail++] = node;
queue->tail %= MAX_QUEUE_SIZE;
}
TreeNode* dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty\n");
return NULL;
}
TreeNode* node = queue->node[queue->head++];
queue->head %= MAX_QUEUE_SIZE;
return node;
}
// 层序遍历
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
Queue* queue = createQueue();
enqueue(queue, root);
while (!isEmpty(queue)) {
int levelSize = queue->tail - queue->head;
for (int i = 0; i < levelSize; i++) {
TreeNode* node = dequeue(queue);
printf("%d ", node->val);
if (node->left) {
enqueue(queue, node->left);
}
if (node->right) {
enqueue(queue, node->right);
}
}
printf("\n");
}
}
// 创建二叉树
TreeNode* createBinaryTree(int* vals, int start, int end) {
if (start > end) {
return NULL;
}
int mid = (start + end) / 2;
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = vals[mid];
root->left = createBinaryTree(vals, start, mid - 1);
root->right = createBinaryTree(vals, mid + 1, end);
return root;
}
int main() {
int vals[] = { 1, 2, 3, 4, 5, 6, 7 };
int len = sizeof(vals) / sizeof(int);
TreeNode* root = createBinaryTree(vals, 0, len - 1);
levelOrder(root);
return 0;
}
```
该程序实现了如何创建二叉树并按层序输出二叉树的值。如果你有任何问题,请在评论区留言,我会尽快回复。
阅读全文