编写C语言算法,判断一个二叉链储存的二叉树是否为完全二叉树
时间: 2024-02-27 15:51:54 浏览: 75
以下是判断一棵二叉树是否为完全二叉树的C语言算法:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
bool isCompleteTree(TreeNode* root) {
if (root == NULL) {
return true;
}
TreeNode* queue[10000];
int front = 0, rear = 0;
bool flag = false;
queue[rear++] = root;
while (front < rear) {
TreeNode* cur = queue[front++];
if (cur->left != NULL) {
if (flag) {
return false;
}
queue[rear++] = cur->left;
} else {
flag = true;
}
if (cur->right != NULL) {
if (flag) {
return false;
}
queue[rear++] = cur->right;
} else {
flag = true;
}
}
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(isCompleteTree(root) ? "是完全二叉树" : "不是完全二叉树");
return 0;
}
```
该算法的思路是通过层序遍历二叉树,在遍历过程中判断是否出现了空节点。如果出现了空节点,那么在后面的节点中不应该再出现非空节点;如果后面出现了非空节点,说明该二叉树不是完全二叉树。
阅读全文