1110 Complete Binary Tree (25 point(s))
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
经验总结:
这一题。。。。真的不难,不论是用DFS还是BFS都可以,不过。。。自己傻了,想着刚做过的PAT 甲级 1102 Invert a Binary Tree 就用了scanf("%c %c"); 那一题题目中结点N<=10而且编号为0~9,可是这一题N<=20。。。。%c只能读取一位啊! 于是自己写了半天,老是无法AC,还以为自己的思想出错了。。。最后才发现是这个错误,以后还是要再仔细一点!不能再犯这么低级的错误了!
AC代码
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int n,k;
struct node
{
int lchild,rchild,no;
}tree[30];
bool flag[30]={false};
int BFS(int x)
{
queue<node> q;
q.push(tree[x]);
int num=1;
while(q.size())
{
node t=q.front();
q.pop();
if(t.lchild==-1&&t.rchild!=-1)
return -1;
else if(t.lchild==-1&&t.rchild==-1)
if(num==n)
return t.no;
else
return -1;
else
{
++num;
if(num==n)
return t.lchild;
q.push(tree[t.lchild]);
if(t.rchild!=-1)
{
++num;
if(num==n)
return t.rchild;
q.push(tree[t.rchild]);
}
}
}
}
int main()
{
char a[3],b[3];
scanf("%d",&n);
int t;
for(int i=0;i<n;++i)
{
tree[i].no=i;
scanf("%s %s",a,b);
if(a[0]!='-')
{
sscanf(a,"%d",&t);
flag[t]=true;
tree[i].lchild=t;
}
else
tree[i].lchild=-1;
if(b[0]!='-')
{
sscanf(b,"%d",&t);
flag[t]=true;
tree[i].rchild=t;
}
else
tree[i].rchild=-1;
}
int root;
for(root=0;root<n;++root)
{
if(flag[root]==false)
break;
}
int f=BFS(root);
if(f!=-1)
printf("YES %d\n",f);
else
printf("NO %d\n",root);
return 0;
}