是否完全二叉搜索树

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值