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
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
栈限制
8192 KB
注意到题目要求就20个节点,因此可以用将节点按顺序填入一维顺序数组中,看其是否为完全二叉树,如果是则数组连续从1到n都有值,否则不是。
其中父节点的左孩子节点位置是 : 父节点位置*2,右节点位置是父节点位置*2+1。
#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
using namespace std;
struct node{
int left = -1,right = -1;
int index = -1;
};
int main(){
int n;
cin >> n;
vector<bool> visit(n,false);
vector<node> v(n);
vector<int> vv(10000,-1);
for(int i = 0; i < n; i++){
string s1,s2;
cin >>s1 >> s2;
if(s1[0]!='-')
{
int d = stoi(s1);
v[i].left = d;
visit[d] = true;
}
if(s2[0]!='-')
{
int d = stoi(s2);
v[i].right = d;
visit[d] = true;
}
}
int root;
for(int i = 0; i < n; i++)
if(!visit[i])
{
root = i;
break;
}
v[root].index = 1;
vv[1] = root;
queue<int> q;
q.push(root);
while(!q.empty()){
int index_node = q.front();
q.pop();
if(v[index_node].left!=-1)
{
int k = v[index_node].left;
v[k].index = v[index_node].index*2;
q.push(k);
vv[v[index_node].index*2] = k;
}
if(v[index_node].right!=-1)
{
int k = v[index_node].right;
v[k].index = v[index_node].index*2+1;
q.push(k);
vv[v[index_node].index*2+1] = k;
}
}
int count1 = 0;
for(int i = 1; i <= n; i++)
if(vv[i]!=-1)
count1++;
if(count1==n)
cout << "YES " <<vv[n];
else cout << "NO "<<root;
return 0;
}