/*************************
题意:
判断所给树是否是完全二叉树
************************/
/***********************
解题思路:
先建立树
建立之后,
把该树按数组树的形式存入数组中(左儿子是i*2,右儿子是i*2+1,根节点是1)
存完之后,检索一下,看看该数组是否是满的,
如果有空缺,说明不是完全二叉树
*************************/
/***********************
笔记:
有一个地方卡了一下:
就是我试着用char读入L和R,然后判断是否等于‘-’
却忘记了可能会输出2位数字的情况,所以不能用char
*********************/
#include<iostream>
#include<stdio.h>
#include<string>
#include<vector>
#include<queue>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<stack>
#include<map>
#include<set>
#include<unordered_map>
using namespace std;
#define M 10005
#define INF 0x7ffffff
int Left[M],Right[M];
int num[M];
void gettree(int root,int i){
if(root == -1)
return ;
num[i] = root;
gettree(Left[root],i*2);
gettree(Right[root],i*2+1);
}
int main(){
int n , m, i;
int L, R;
int rootflag[150];
memset(rootflag,0,sizeof(rootflag));
cin>>n;
for(i = 1;i <= n;i++)
num[i] = -1;
string SL,SR;
for(i = 0;i < n; i++){
cin>>SL>>SR;
if(SL[0] == '-')
Left[i] = -1;
else{
L = atoi(SL.c_str());
Left[i] = L ;
rootflag[L] = 1;
}
if(SR[0] == '-')
Right[i] = -1;
else{
R = atoi(SR.c_str());
Right[i] = R ;
rootflag[R] = 1;
}
}
int root;
for(i = 0;i<n;i++)
if(rootflag[i] == 0)
root = i;
int f;
gettree(root, 1);
for(i = 1;i <= n;i++)
if(num[i] == -1)
break;
if(i == n+1){
printf("YES %d\n",num[n]);
}
else{
printf("NO %d\n",root);
}
return 0;
}
PAT 1110. Complete Binary Tree (25) 完全二叉树判断
最新推荐文章于 2020-07-23 16:07:23 发布