Given a tree, you are supposed to tell if it is a complete binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤20) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a -
will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each case, print in one line YES
and the index of the last node if the tree is a complete binary tree, or NO
and the index of the root if not. There must be exactly one space separating the word and the number.
Sample Input 1:
9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -
Sample Output 1:
YES 8
Sample Input 2:
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
Sample Output 2:
NO 1
#include <stdio.h>
#include <algorithm>
#include <set>
#include <string.h>
#include <vector>
#include <math.h>
#include <queue>
#include <iostream>
#include <string>
using namespace std;
const int maxn = ;
int n,k;
struct node{
int l=-,r=-;
}tree[maxn];
int vis[maxn]={};
int main(){
scanf("%d",&n);
getchar();
for(int i=;i<n;i++){
string c1,c2;
cin>>c1>>c2;
getchar();
int n1=-,n2=-;
if(c1!="-"){
n1=stoi(c1);
vis[n1]=;
}
if(c2!="-"){
n2=stoi(c2);
vis[n2]=;
}
tree[i].l=n1;
tree[i].r=n2;
}
int root=-;
for(int i=;i<n;i++){
if(vis[i]==){
root=i;
break;
}
}
int flag=,flag2=,now;
queue<int> q;
q.push(root);
while(!q.empty()){
now=q.front();
q.pop();
//printf("%d ",now);
if(tree[now].l!=-){
if(flag==)q.push(tree[now].l);
else {
flag2=;
break;
}
}
else{
flag=;
}
if(tree[now].r!=-){
if(flag==)q.push(tree[now].r);
else {
flag2=;
break;
}
}
else{
flag=;
}
/*if(now!=-1){
flag++;
flag2=now;
}
else{
if(flag==n){
printf("YES %d",flag2);
}
else{
printf("NO %d",root);
}
return 0;
}
q.push(tree[now].l);
q.push(tree[now].r);
*/
}
if(flag2==)printf("NO %d",root);
else printf("YES %d",now);
}
注意点:完全二叉树的判断就是看已经有节点没孩子了,后面节点却还有孩子,这树就不是完全二叉树。有三个点一直错误,一开始段错误,后来在结构体初始化了-1后答案错误,总找不到原因。后来才发现原来是读输入的时候错了,两位数就读不到了,不能用%c,要用string