visualstudio判断是否为完全二叉树
时间: 2024-01-07 22:23:40 浏览: 28
以下是判断是否为完全二叉树的函数示例:
```c++
#include <iostream>
#include <queue>
using namespace std;
struct BtNode {
int data;
BtNode* leftchild;
BtNode* rightchild;
};
bool IsCompleteBinaryTree(BtNode* root) {
if (root == NULL) {
return true;
}
queue<BtNode*> q;
q.push(root);
bool flag = false;
while (!q.empty()) {
BtNode* current = q.front();
q.pop();
if (current->leftchild != NULL) {
if (flag == true) {
return false;
}
q.push(current->leftchild);
} else {
flag = true;
}
if (current->rightchild != NULL) {
if (flag == true) {
return false;
}
q.push(current->rightchild);
} else {
flag = true;
}
}
return true;
}
int main() {
// 创建一个完全二叉树
BtNode* root = new BtNode();
root->data = 1;
root->leftchild = new BtNode();
root->leftchild->data = 2;
root->rightchild = new BtNode();
root->rightchild->data = 3;
root->leftchild->leftchild = new BtNode();
root->leftchild->leftchild->data = 4;
root->leftchild->rightchild = new BtNode();
root->leftchild->rightchild->data = 5;
// 判断是否为完全二叉树
if (IsCompleteBinaryTree(root)) {
cout << "This is a complete binary tree." << endl;
} else {
cout << "This is not a complete binary tree." << endl;
}
return 0;
}
```