一般在用队列进行层序遍历时候,遇到node 左右子树为-1时,是return的,但如果要检查一棵树是不是完全二叉树,就不用return了,而是把-1也压进队列,如果在遍历的中途,队列中出现了-1,即说明不是完全二叉树。如果要检查是否为满二叉树,判断遍历完成后,node数是否等于2的level次-1即可。
#include <iostream>
#include <queue>
#include <cctype>
using namespace std;
const int maxn = 30;
struct node{
int lchild = -1, rchild = -1;
}Node[maxn];
int isroot[maxn] = {0};
int main(){
int n, root;
string s1, s2;
cin >> n;
for(int i = 0; i < n; i++){
cin >> s1 >> s2;
if(isdigit(s1[0])){
isroot[stoi(s1)] = 1;
Node[i].lchild = stoi(s1);
}
if(isdigit(s2[0])){
isroot[stoi(s2)] = 1;
Node[i].rchild = stoi(s2);
}
}
for(int i = 0; i < n; i++) if(isroot[i] == 0) root = i;
queue<int> q;
q.push(root);
int cnt = 0, lastnode;
while(!q.empty()){
int now = q.front();
q.pop();
if(now != -1){
cnt++; lastnode = now;
}else{
if(cnt == n) printf("YES %d", lastnode);
else printf("NO %d", root);
break;
}
q.push(Node[now].lchild);
q.push(Node[now].rchild);
}
return 0;
}