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
题意:给出一棵二叉树,让你判断它是否是一棵完全二叉树,如果是输出yes,并输出最后一个结点编号,否则输出no并输出根节点编号。
思路:首先建立二叉树,然后使用层序遍历,把所有非空结点的孩子节点压入队列中,直到碰到空结点此时如果队列中还有非空结点则该树不是完全二叉树。 根节点一定不会出现在其他结点的子节点中,根据这一特性可以求出根节点编号。
注意:输入时由于结点范围是0-25,可能为两位数,因此不能使用单个字符读入子节点编号。
参考代码:
#include<cstdio>
#include<string>
#include<iostream>
#include<queue>
using namespace std;
int n,root=0,last=-1,hasht[25];
struct node{
int lchild,rchild;
node(int a=-1,int b=-1):lchild(a),rchild(b){}
}T[25];
bool judge(){
bool flag=true;
queue<int> q;
q.push(root);
while(!q.empty()){
int p=q.front();
q.pop();
if(p!=-1){
last=p;
q.push(T[p].lchild);
q.push(T[p].rchild);
}else{
while(!q.empty()){
int t=q.front();
q.pop();
if(t!=-1) //如果队列中还有非空结点,说明不是完全二叉树
flag=false;
}
}
}
return flag;
}
int main()
{
scanf("%d",&n);
string a,b;
for(int i=0;i<n;i++){
cin>>a>>b;
if(a!="-") {
int t=stoi(a,0,10);
T[i].lchild=t;
hasht[t]=1;
}
if(b!="-"){
int t=stoi(b,0,10);
T[i].rchild=t;
hasht[t]=1;
}
}
while(root<n&&hasht[root]) root++; //寻找根节点
if(judge()) printf("YES %d\n",last);
else printf("NO %d\n",root);
return 0;
}