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
思路:用并查集找到树的根,然后宽度优先搜索,判断一下第一次出现没有左子节点的节点是不是第n个节点,就可以知道是不是完全二叉树。
#include<bits/stdc++.h>
using namespace std;
struct node{
int l,r,n;
node(){
l=-1, r=-1;
}
};
node t[50];
int bin[50];
int findfa(int x){
if(bin[x]==x) return x;
else return findfa(bin[x]);
}
int main(){
int n;
cin>>n;
for(int i=0; i<n; ++i) bin[i]=i;
for(int i=0; i<n; ++i){
string a, b;
cin>>a>>b;
if(a!="-"){
t[i].l=stoi(a);
bin[stoi(a)]=i;
}
if(b!="-"){
t[i].r=stoi(b);
bin[stoi(b)]=i;
}
t[i].n=i;
}
int root = findfa(0);
int cnt=1;
queue<int> q;
q.push(root);
int now;
int f=0, time=0;
while(!q.empty()){
now = q.front();
q.pop();
if(t[now].l!=-1){
q.push(t[now].l);
cnt++;
}else if(time==0){
if(cnt==n) f=1;
time=1;
}
if(t[now].r!=-1){
q.push(t[now].r);
cnt++;
}
}
if(!f) cout<<"NO "<<root<<endl;
else cout<<"YES "<<now<<endl;
return 0;
}