又是完全二叉树,在课上瞎弄了很久,马上就要考PAT了,感觉凶多吉少,老天保佑,赐我个满分吧!!!
1110. Complete Binary Tree (25)
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 8Sample Input 2:
8 - - 4 5 0 6 - - 2 3 - 7 - - - -Sample Output 2:
NO 1
解题思路:开两个数组分别记录节点高度和节点父亲。父节点是自己的,则是根。满足:1.有右无左 2.右高左低 3.左比右高2以上 这三个条件之一的就不是完全二叉树。我用宽搜,一层一层去判断这些条件,最后一个搜索到的节点就是最后一片叶子。
上代码,注意看注释:
#include<iostream>
#include<cstdio>
#include<string>
#include<string.h>
#include<vector>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
int N;
int height[25],fa[25];
char L[2],R[2];
int l,r;
vector<int> vv[22];
bool flag=true;
int last;
queue<int> que;
//讲解点好转成数字 如果是- 即无该子节点 则返回24 由于数据限制 不会出现24这个节点号
int toInt(char arg[])
{
if(strcmp(arg,"-")==0)
return 24;
int len=strlen(arg);
int ans=0;
for(int i=0;i<len;i++)
{
ans=ans*10+arg[i]-'0';
}
return ans;
}
//更新父节点高度
void upFa(int x)
{
if(x!=fa[x])
{
height[fa[x]]=max(height[x]+1, height[fa[x]]);
upFa(fa[x]);
}
}
//宽度优先搜索判断是否是二叉树
void BFS(int root)
{
/*
1.有右无左 2.右高左低 3.左比右高2以上
*/
que.push(root);
int now;
while(!que.empty())
{
now=que.front();
que.pop();
int ll=vv[now][0],rr=vv[now][1];
if(ll==24 && rr!=24)
{
flag=false;
}
else if(height[ll]<height[rr])
{
flag=false;
}
else if(height[ll]>height[rr]+1)
{
flag=false;
}
if(ll!=24)
que.push(ll);
if(rr!=24)
que.push(rr);
}
last=now;
}
int main()
{
for(int i=0;i<=20;i++)
fa[i]=i;
scanf("%d",&N);
for(int i=0;i<N;i++)
{
scanf("%s",L);
l=toInt(L);
scanf("%s",R);
r=toInt(R);
vv[i].push_back(l);
vv[i].push_back(r);
height[i]=max(height[l],height[r]+1);
fa[l]=fa[r]=i; //设置父亲节点
upFa(i);
}
int j;
for(j=0;j<N;j++)
if(fa[j]==j)
break;
BFS(j);
if(flag)
{
printf("YES %d\n",last);
}
else
{
printf("NO %d\n",j);
}
return 0;
}