PTA:L3-010 是否完全二叉搜索树

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值