用c语言写一个完全二叉树
时间: 2024-06-06 13:02:18 浏览: 94
以下是用C语言实现完全二叉树的代码,其中包括创建完全二叉树、层次遍历以及判断是否为完全二叉树的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
// 定义二叉树结点
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 定义队列结构体
typedef struct Queue {
TreeNode *data[MAXSIZE];
int front, rear;
} Queue;
// 初始化队列
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
// 判断队列是否为空
int isEmpty(Queue *q) {
return q->front == q->rear;
}
// 入队
void enQueue(Queue *q, TreeNode *node) {
if ((q->rear + 1) % MAXSIZE == q->front) {
printf("Queue is full.\n");
return;
}
q->data[q->rear] = node;
q->rear = (q->rear + 1) % MAXSIZE;
}
// 出队
TreeNode *deQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return NULL;
}
TreeNode *node = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return node;
}
// 创建完全二叉树
TreeNode *createCompleteBinaryTree(int *arr, int size, int index) {
if (index >= size) {
return NULL;
}
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->data = arr[index];
root->left = createCompleteBinaryTree(arr, size, 2 * index + 1);
root->right = createCompleteBinaryTree(arr, size, 2 * index + 2);
return root;
}
// 层次遍历
void levelOrderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
Queue q;
initQueue(&q);
enQueue(&q, root);
while (!isEmpty(&q)) {
TreeNode *node = deQueue(&q);
printf("%d ", node->data);
if (node->left != NULL) {
enQueue(&q, node->left);
}
if (node->right != NULL) {
enQueue(&q, node->right);
}
}
}
// 判断是否为完全二叉树
int isCompleteBinaryTree(TreeNode *root) {
if (root == NULL) {
return 1;
}
Queue q;
initQueue(&q);
enQueue(&q, root);
int flag = 0;
while (!isEmpty(&q)) {
TreeNode *node = deQueue(&q);
if (node == NULL) {
flag = 1;
} else {
if (flag == 1) {
return 0;
}
enQueue(&q, node->left);
enQueue(&q, node->right);
}
}
return 1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);
TreeNode *root = createCompleteBinaryTree(arr, size, 0);
printf("层次遍历结果为:");
levelOrderTraversal(root);
printf("\n");
if (isCompleteBinaryTree(root)) {
printf("该二叉树是完全二叉树。\n");
} else {
printf("该二叉树不是完全二叉树。\n");
}
return 0;
}
```
阅读全文