完全二叉樹的判定方法:進行層次遍歷,並且讓空結點也入隊,如果在訪問完N個非空結點之前訪問到了空結點,那麼說明不是完全二叉樹。
一個測試點過不了:發現是因爲我通過返回值是否是root來判斷是否爲二叉樹,而當n=1即只有一個根結點的情況下,返回的一定是root,此情況需特判.
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
int n;
bool isroot[25]={false},flag=false;
struct node{
int lchild;
int rchild;
}nodes[25];
int change(char c[3]){
int len=strlen(c);
int sum;
if(len==2){
sum=10*(c[0]-'0')+c[1]-'0';
isroot[sum]=true;
return sum;
}
if(c[0]=='-'){
return -1;
}else{
sum=c[0]-'0';
isroot[sum]=true;
return sum;
}
}
int findroot(){
for(int i=0;i<n;i++){
if(isroot[i]==false)return i;
}
}
int BFS(int root){
int num=0,pre;
queue<int> q;
q.push(root);
while(!q.empty()){
int now=q.front();
q.pop();
if(now==-1){
if(num==n){
return pre;
}
return root;
}
num++;
q.push(nodes[now].lchild);
q.push(nodes[now].rchild);
pre=now;
}
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
char c1[3],c2[3];
scanf("%d",&n);
for(int i=0;i<n;i++){
getchar();
scanf("%s %s",c1,c2);
nodes[i].lchild=change(c1);
nodes[i].rchild=change(c2);
}
int root=findroot();
int res=BFS(root);
if(res==root){
printf("NO %d",res);
}else{
printf("YES %d",res);
}
return 0;
}
算法筆記(能AC):兩段代碼唯一不同的是BFS函數
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
int n;
bool isroot[25]={false};
struct node{
int lchild;
int rchild;
}nodes[25];
int change(char c[3]){
int len=strlen(c);
int sum;
if(len==2){
sum=10*(c[0]-'0')+c[1]-'0';
isroot[sum]=true;
return sum;
}
if(c[0]=='-'){
return -1;
}else{
sum=c[0]-'0';
isroot[sum]=true;
return sum;
}
}
int findroot(){
for(int i=0;i<n;i++){
if(isroot[i]==false)return i;
}
}
bool BFS(int root,int &last){
queue<int> q;
q.push(root);
while(n){
int front=q.front();
q.pop();
if(front==-1){
return false;
}
n--;
last=front;
q.push(nodes[front].lchild);
q.push(nodes[front].rchild);
}
return true;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
char c1[3],c2[3];
scanf("%d",&n);
for(int i=0;i<n;i++){
getchar();
scanf("%s %s",c1,c2);
nodes[i].lchild=change(c1);
nodes[i].rchild=change(c2);
}
int root=findroot(),last;
bool isCompleteTree=BFS(root,last);
if(!isCompleteTree){
printf("NO %d",root);
}else{
printf("YES %d",last);
}
return 0;
}