PTA:L3-010
题解:先构建一棵二叉搜索树,注意是左边大右边小。判断是否是完全二叉树的方法是:如果是完全二叉树,那么层次遍历正好遍历n个结点,而且没有空结点。
代码:指针版
#include <bits/stdc++.h>
using namespace std;
int const N = 20 + 5;
int a[N],n,pos;
typedef struct Node
{
Node *left,*right;
int val;
}*Tree;
void insert(Tree &root,int element){
if(root == NULL){
root = new Node();
root->left = root->right = NULL;
root->val = element;
}else{
if(element < root->val) insert(root->right,element);
else insert(root->left,element);
}
}
queue<Tree>q;
void display(Tree root){
q.push(root);
bool flag = true;
int cnt = 0;
while(!q.empty()){
Tree p = q.front(); q.pop(); cnt++;
if(p == NULL) continue;
if(cnt > n) flag = false;
if(p == root) printf("%d",p->val);
else printf(" %d",p->val);
q.push(p->left);
q.push(p->right);
}
printf("\n");
if(flag) printf("YES\n");
else printf("NO\n");
}
int main(){
cin>>n;
Tree root = NULL;
for(int i=0;i<n;i++){
int tmp; cin>>tmp;
insert(root,tmp);
}
display(root);
}
数组版
#include <bits/stdc++.h>
using namespace std;
int const N = 2100000;
int a[N],n;
void insert(int pos,int val){
if(a[pos] == 0) a[pos] = val;
else{
if(val > a[pos]) insert(2*pos,val);
else insert(2*pos+1,val);
}
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
int tmp; cin>>tmp;
insert(1,tmp);
}
bool flag = true;
int cnt = 0;
for(int i=1;i<N;i++){
if(a[i]){
printf("%d%c",a[i],++cnt != n ? ' ':'\n');
if(i > n) flag = false;
}
}
if(flag) printf("YES\n");
else printf("NO\n");
return 0;
}