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
#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
#include<cmath>
#include<algorithm>
using namespace std;
struct node
{
int data;
node * lchild;
node * rchild;
int index;
};
vector<int> vec[1000];
node * creat_tree(int start){
if(start == -1){
return NULL;
}
node * root = new node();
root -> data = start;
root -> lchild = creat_tree(vec[start][0]);
root -> rchild = creat_tree(vec[start][1]);
return root;
}
node * level_order(node * tree){
queue<node *> que;
node * last_node = new node();
tree -> index = 1;
last_node = tree;
que.push(tree);
while (!que.empty())
{
// cout << que.front() -> data << endl;
if(que.front() -> lchild != NULL){
que.front() -> lchild -> index = 2 * que.front() -> index;
last_node = que.front() -> lchild;
que.push(que.front() -> lchild);
}
if(que.front() -> rchild != NULL){
que.front() -> rchild -> index = 2 * que.front() -> index + 1;
last_node = que.front() -> rchild;
que.push(que.front() -> rchild);
}
que.pop();
}
return last_node;
}
int main(){
int n;
bool visit[1000] = {false};
cin >> n;
for(int i = 0; i < n; i++){
string a, b;
cin >> a >> b;
if(a == "-"){
vec[i].push_back(-1);
}else
{
vec[i].push_back(stoi(a));
visit[stoi(a)] = true;
}
if(b == "-"){
vec[i].push_back(-1);
}else
{
vec[i].push_back(stoi(b));
visit[stoi(b)] = true;
}
}
int flag;
for(int i = 0; i < n; i++){
if(!visit[i]){
flag = i;
break;
}
}
node * tree = creat_tree(flag);
if(level_order(tree) -> index == n){
printf("YES %d\n", level_order(tree) -> data);
}else
{
printf("NO %d\n", flag);
}
return 0;
}