判断一棵树是否为完全二叉树,用C语言实现
时间: 2023-06-11 08:06:19 浏览: 141
可以使用层次遍历(广度优先搜索)的方式来判断一棵树是否为完全二叉树。具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
bool isCompleteTree(TreeNode* root) {
if (root == NULL) {
return true;
}
bool flag = false; // 是否遇到过不满足完全二叉树的情况
TreeNode* queue[10000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
TreeNode* node = queue[front++];
if (node == NULL) {
flag = true;
} else {
if (flag) { // 如果已经遇到过空节点,那么当前节点不应该存在左右子节点
return false;
}
queue[rear++] = node->left;
queue[rear++] = node->right;
}
}
return true;
}
int main() {
// 构造一棵完全二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
printf("%d\n", isCompleteTree(root)); // 输出1,表示是完全二叉树
// 构造一棵不完全的二叉树
TreeNode* root2 = (TreeNode*)malloc(sizeof(TreeNode));
root2->val = 1;
root2->left = (TreeNode*)malloc(sizeof(TreeNode));
root2->left->val = 2;
root2->right = (TreeNode*)malloc(sizeof(TreeNode));
root2->right->val = 3;
root2->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root2->left->left->val = 4;
printf("%d\n", isCompleteTree(root2)); // 输出0,表示不是完全二叉树
return 0;
}
```
上述代码中,使用一个flag变量来记录是否遇到过空节点,如果遇到了,后面所有的节点都不应该存在左右子节点。如果在遍历过程中发现当前节点为NULL,就将flag设置为true;否则,如果已经遇到了空节点,就返回false;否则,就将当前节点的左右子节点加入到队列中。
阅读全文