PAT (Advanced Level) Practice 1110 Complete Binary Tree (25 分)
阿新 • • 發佈:2018-12-07
#include<cstdio>
#include<queue>
using namespace std;
const int N=20+5;
int ch[N][2],vis[N];
int bfs(int s)
{
queue<int> q;
q.push(s);
int pre=1,last;
while(!q.empty())
{
int u=q.front();
last=u;
q.pop();
if(!ch[u][0]&& ch[u][1]) return 0;
if(ch[u][0]&&ch[u][1]&&!pre) return 0;
if(!ch[u][0]&&!ch[u][1]||ch[u][0]&&!ch[u][1]) pre=0;
if(ch[u][0]) q.push(ch[u][0]);
if(ch[u][1]) q.push(ch[u][1]);
}
return last;
}
int main()
{
int n;scanf("%d",&n);
for (int i=1;i<=n;i++)
{
char s1[10],s2[10];
scanf("%s%s",s1,s2);
if(s1[0]!='-') sscanf(s1,"%d",&ch[i][0]),ch[i][0]++,vis[ch[i][0]]=1;
if(s2[0]!='-') sscanf(s2,"%d",&ch[i][1]),ch[i][1]++,vis[ch[i][1]]=1;
}
int rt;
for(int i=1;i<=n;i++)
if(!vis[ i])
rt=i;
int now=bfs(rt);
if(now) printf("YES %d",now-1);
else printf("NO %d",rt-1);
return 0;
}