判断一棵二叉树是否为完全二叉树
可以通过层次遍历来实现。以下是一个基于思路的算法:
从根节点开始,进行层次遍历。
对于每个遍历到的节点,依次执行以下步骤:
如果当前节点有左子节点,将左子节点加入遍历队列。
如果当前节点没有左子节点但有右子节点,那么该二叉树不是完全二叉树。
如果当前节点没有左子节点也没有右子节点,那么之后的所有节点都必须是叶子节点,否则该二叉树不是完全二叉树。
如果层次遍历完所有节点后没有违反上述条件,那么该二叉树是完全二叉树。
通过以上算法,我们可以判断一棵二叉树是否为完全二叉树。在具体实现时,你可以使用队列来辅助层次遍历,并记录是否遇到了非叶子节点。
#include <stdio.h>
#include <stdlib.h>
#define max_size 100
typedef struct TreeNode {
int value;
struct TreeNode* left;
struct TreeNode* right;
} *Tree;
typedef struct Queue {
Tree* base;
int front;
int rear;
int maxsize;
} Queue;
int InitQueue(Queue* Q) {
Q->base = (Tree*)malloc(max_size * sizeof(Tree));
if (!Q->base) {
return 0;
}
Q->front = Q->rear = 0;
Q->maxsize = max_size;
return 1;
}
void inQueue(Queue* Q, Tree a) {
Q->base[Q->rear] = a;
Q->rear = (Q->rear + 1) % Q->maxsize;
}
Tree deQueue(Queue* Q) {
Tree e = Q->base[Q->front];
Q->front = (Q->front + 1) % Q->maxsize;
return e;
}
int isCompleteTree(Tree T) {
Queue Q;
if (!InitQueue(&Q)) {
return 0; // 队列初始化失败
}
inQueue(&Q, T);
int flag = 0; // 用于标记是否出现空节点
while (Q.front != Q.rear) {
Tree current = deQueue(&Q);
if (current == NULL) {
flag = 1;
}
else {
if (flag == 1) {
// 如果之前出现过空节点,当前节点不应该存在子节点
return 0; // 不是完全二叉树
}
if (current->left != NULL) {
inQueue(&Q, current->left);
}
if (current->right != NULL) {
inQueue(&Q, current->right);
}
}
}
return 1; // 是完全二叉树
}
int main() {
// 创建一棵二叉树并进行判断
// 在这里创建您的二叉树
if (isCompleteTree(your_tree_root)) {
printf("The tree is a complete binary tree.\n");
}
else {
printf("The tree is not a complete binary tree.\n");
}
return 0;
}