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 8
Sample Input 2
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
Sample Output 2
NO 1
题意
判断一棵树是否为完全二叉树,是则输出YES以及最后一个结点的索引号,否则输出NO以及根结点的索引号。
判断是否为二叉树要注意:
1.当前节点有右孩子,但没有左孩子,直接返回false
2.当前节点有左孩子没右孩子,那么接下来遇到的所有节点必须是叶子节点,否则返回false
代码
#include <iostream>
#include <string>
#include <queue>
using namespace std;
struct node {
string left,right;
int layer;
} Node[21];
int n;
string tmp;
bool book[21]= {false};
bool isCBT(string root) {
queue<string> q;
q.push(root);
bool isleaf=false;
while(!q.empty()) {
string now=q.front();
q.pop();
int id=stoi(now);
tmp = now;
string l=Node[id].left;
string r=Node[id].right;
//当前节点有右孩子,但没有左孩子,直接返回false
//当前节点有左孩子没右孩子,那么接下来遇到的所有节点必须是叶子节点
if((isleaf && (l!="-" || r!="-")) || (l=="-" && r!="-"))
return false;
if(l!="-") q.push(l);
if(r!="-") q.push(r);
if(l=="-" && r=="-") isleaf=true;
}
return true;
}
int main() {
scanf("%d",&n);
string l,r,s; //s存放根结点
for(int i=0; i<n; i++) {
cin >> l >> r;
Node[i].left=l;
Node[i].right=r;
if(l!="-") book[stoi(l)]=true;
if(r!="-") book[stoi(r)]=true;
}
for(int i=0; i<n; i++) {
if(book[i]==false) {
s=to_string(i);
break;
}
}
if(isCBT(s)) {
printf("YES %s",tmp.c_str());
} else {
printf("NO %s",s.c_str());
}
return 0;
}