7-13 是否完全二叉搜索树 (30分)
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES,如果该树是完全二叉树;否则输出NO。
输入样例1:
9
38 45 42 24 58 30 67 12 51
输出样例1:
38 45 24 58 42 30 12 67 51
YES
输入样例2:
8
38 24 12 45 58 67 42 51
输出样例2:
38 45 24 58 42 12 67 51
NO
顺序存储解法
#include<iostream>
#include<cstring>
using namespace std;
int a[10005];
void add(int i,int &d)
{
if(a[i]==-1)
{
a[i]=d;
return;
}
if(d>a[i]) add(i*2,d);
else add(i*2+1,d);
}
int main()
{
int n,d;
cin>>n;
memset(a,-1,sizeof(a));
for(int i=0;i<n;i++)
{
cin>>d;
add(1,d);
}
int cnt=0,i=0;
while(cnt<n)
{
while(a[i]==-1) i++;
if(cnt==0) cout<<a[i];
else cout<<" "<<a[i];
cnt++;i++;
}
if(i==n+1)
cout<<"\nYES";
else
cout<<"\nNO";
return 0;
}
链式存储解法
更多详细说明链接:https://blog.csdn.net/qq_37383726/article/details/79716739
#include<bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 1E5+11;
const int M = 1E6+11;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;
typedef struct Tree{
int val;
struct Tree *lson;
struct Tree *rson;
}*ptree;
void Build(ptree &rt,int x){
if(rt==NULL) {
rt=new Tree();
rt->val=x;
return ;
}
if(rt->val>x) Build(rt->rson,x);
else Build(rt->lson,x);
}
bool Bfs(ptree rt){
queue<ptree>que;
que.push(rt); int have=0;
bool ff=false; // 表示是否要为叶子节点
bool flag=true; // 是否为完全二叉树
while(!que.empty()){
ptree now =que.front(); que.pop();
if(ff){ // 表示以后所有节点都要是叶子节点才可以
if(now->lson || now->rson)
flag=false;
}
if(now->rson && !now->lson) flag=false; // 有右 没有左
if(now->lson && !now->rson) ff=true; // 有左没有右
if(!now->lson && !now->rson) ff=true; // 左右都没有
if(have++) putchar(' ');
printf("%d",now->val);
if(now->lson) que.push(now->lson);
if(now->rson) que.push(now->rson);
}
return flag;
}
int main(){
int n;scanf("%d",&n);
ptree rt=NULL;
for(int i=1;i<=n;i++){
int t;scanf("%d",&t);
Build(rt,t);
}
if(Bfs(rt)) puts("\nYES");
else puts("\nNO");
return 0;
}