用C语言编写一算法,判别给定二叉树是否为完全二叉树。
时间: 2024-03-24 17:36:14 浏览: 100
以下是使用C语言编写的判断给定二叉树是否为完全二叉树的算法:
```c
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
bool isCompleteBinaryTree(struct Node* root) {
if (root == NULL) {
return true;
}
bool end = false;
struct Node* queue[1000]; // 假设二叉树节点数不超过1000
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
struct Node* node = queue[front++];
if (node->left != NULL) {
if (end) {
return false;
}
queue[rear++] = node->left;
} else {
end = true;
}
if (node->right != NULL) {
if (end) {
return false;
}
queue[rear++] = node->right;
} else {
end = true;
}
}
return true;
}
int main() {
// 构造一棵完全二叉树
struct Node* root = (struct Node*) malloc(sizeof(struct Node));
root->data = 1;
root->left = (struct Node*) malloc(sizeof(struct Node));
root->left->data = 2;
root->left->left = (struct Node*) malloc(sizeof(struct Node));
root->left->left->data = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (struct Node*) malloc(sizeof(struct Node));
root->left->right->data = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (struct Node*) malloc(sizeof(struct Node));
root->right->data = 3;
root->right->left = (struct Node*) malloc(sizeof(struct Node));
root->right->left->data = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = NULL;
// 判断是否为完全二叉树
bool isComplete = isCompleteBinaryTree(root);
if (isComplete) {
printf("The binary tree is a complete binary tree.\n");
} else {
printf("The binary tree is not a complete binary tree.\n");
}
return 0;
}
```
该算法首先检查树是否为空。如果为空,则它是一棵完全二叉树。如果不为空,则使用一个队列来遍历该树。如果一个节点有左子节点但没有右子节点,或者一个节点没有左子节点和右子节点,则接下来遍历的节点必须都是叶子节点。如果一个节点已经满足这个条件,但接下来遍历的节点不都是叶子节点,则该树不是完全二叉树。否则,该树是一棵完全二叉树。
阅读全文