满二叉树:
(int)(pow(2,step))需要加上int转换。
#include <cstdio>
#include <queue>
#include <cmath>
using namespace std;
const int N = 70;
struct binarynode{
int left;
int right;
}nodes[N];
int isfullbinaryTree(int root) {
int step = 0;
queue<int> q;
q.push(root);
while (!q.empty()){
int cnt = q.size();
if (cnt == (int)(pow(2,step))){
while (cnt--){
int temp = q.front();
q.pop();
if (nodes[temp].left != -1)q.push(nodes[temp].left);
if (nodes[temp].right != -1)q.push(nodes[temp].right);
}
}else return 0;
step++;
}
return 1;
}
int main(){
int n;
scanf("%d",&n);
for (int i=0;i<n;i++){
scanf("%d%d",&nodes[i].left,&nodes[i].right);
}
printf("%s",isfullbinaryTree(0) ? "Yes":"No");
return 0;
}
完全二叉树:
如果出现空树,就不能再出现非空树
#include <cstdio>
#include <queue>
using namespace std;
const int N = 70;
struct binaryTree{
int left;
int right;
}nodes[N];
int BFS(int root){
queue<int> q;
q.push(root);
int getnullnode = 0;
while (!q.empty()){
int temp = q.front();
q.pop();
if (temp!=-1 && getnullnode == 1){
return 0;
}
if (temp == -1){
getnullnode = 1;
}else {
q.push(nodes[temp].left);
q.push(nodes[temp].right);
}
}
return 1;
}
int main(){
int n;
scanf("%d",&n);
for (int i=0;i<n;i++){
scanf("%d%d",&nodes[i].left,&nodes[i].right);
}
printf("%s",BFS(0)?"Yes":"No");
return 0;
}