题目描述
知识点: 完全二叉树,层序遍历
思路: 本题为判断完全二叉树,可以先层序遍历这个树,然后依次将值填入数组中。然后利用这个数组使用完全二叉树的性质判断这个树是不是完全二叉树。(如果是的话这个数组应该是符合完全二叉树的)
#include<iostream>
#include<queue>
using namespace std;
const int N = 50;
int l[N],r[N],node[N],not_root[N];
int n;
void bfs(int u){
int cur = 1;
queue<int> q;
q.push(u);
while(!q.empty()){
int f = q.front();
q.pop();
node[cur++] = f;
if(l[f]) q.push(l[f]);
if(r[f]) q.push(r[f]);
}
}
int main(){
cin>>n;
for(int i = 1;i <= n;i++){
string l_c,r_c;
cin>>l_c>>r_c;
if(l_c != "-")
{
int nl_c = stoi(l_c);;
l[i] = nl_c+1;
not_root[nl_c+1] = 1;
}
if(r_c != "-"){
int nr_c = stoi(r_c);
r[i] = nr_c+1;
not_root[nr_c+1] = 1;
}
}
int root = -1;
for(int i = 1;i <= n;i++) if(not_root[i] == 0) root = i;
bfs(root);
bool is_complete_tree = true;
for(int i = 1;i <= n;i++){
int u = node[i];
if(u == 0) is_complete_tree = false;
if(2*i <= n && node[2*i] != l[u]) is_complete_tree = false;
if(2*i+1 <= n && node[2*i+1] != r[u]) is_complete_tree = false;
}
if(is_complete_tree)
cout<<"YES"<<" "<<node[n]-1;
else
cout<<"NO"<<" "<<root-1;
return 0;
}