【PAT 甲级】A1043 Is It a Binary Search Tree(25分)

PAT坑点提示!(当然也可能是我太笨了qwq):定义全局变量的时候一定不要用index这个标识符,否则会提示编译错误!!
原因貌似是用了#include <bits/stdc++.h>,这个头文件貌似已经定义了一些标识符,所以冲突了。当然我在Dev-C++上还是运行良好的…
【版本一:没读明白题就做了,死得很惨,17分】
代码不展示了,连给的样例测试点2都没过hhhh
【版本二:这个题其实就考察了BST的构造和遍历…应该还是算水题的吧…我做得忒麻烦了,25分】

#include <bits/stdc++.h>
using namespace std;
int num[1001];
int pre[1001];
int mir[1001];
int post[1001];
int pointer=0;
struct node
{
	int key;
	node* left;
	node* right;
};
node* insert(node* root,int key)
{
	if(root==NULL)
	{
		root=new node;
		root->key=key;
		root->left=NULL;
		root->right=NULL;
		return root;
	}
	if(root->key > key)
	{
		if(root->left == NULL)
		{
			root->left=insert(root->left,key);
		}
		else insert(root->left,key);
	}
	else
	{
		if(root->right == NULL)
		{
			root->right=insert(root->right,key);
		}
		else insert(root->right,key);
	}
	return root;
}
node* insert2(node* root,int key)
{
	if(root==NULL)
	{
		root=new node;
		root->key=key;
		root->left=NULL;
		root->right=NULL;
		return root;
	}
	if(root->key <= key)
	{
		if(root->left == NULL)
		{
			root->left=insert2(root->left,key);
		}
		else insert2(root->left,key);
	}
	else
	{
		if(root->right == NULL)
		{
			root->right=insert2(root->right,key);
		}
		else insert2(root->right,key);
	}
	return root;
}

void preorder(node* root)
{
	if(!root) return;
	pre[pointer]=root->key;
	pointer++;
	preorder(root->left);
	preorder(root->right);
}
void mirror(node* root)
{
	if(!root) return;
	mir[pointer]=root->key;
	pointer++;
	mirror(root->left);
	mirror(root->right);
}
void postorder(node* root)
{
	if(!root) return;
	postorder(root->left);
	postorder(root->right);
	post[pointer]=root->key;
	pointer++;
}
int main(void)
{
	int n;
	node* root=NULL;
	node* root2=NULL;
	bool pflag=true,mflag=true;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&num[i]);
		root=insert(root,num[i]);
		root2=insert2(root2,num[i]);
	}
	pointer=0; preorder(root);
	pointer=0; mirror(root2);
	for(int i=0;i<n;i++)
	{
		if(num[i]!=pre[i])
		{
			pflag=false;
		}
		if(num[i]!=mir[i])
		{
			mflag=false;
		}
	}
	if(!mflag && !pflag)
	{
		printf("NO");
	}
	else if(pflag)
	{
		pointer=0; postorder(root);
		printf("YES\n");
		for(int i=0;i<n;i++)
		{
			printf("%d",post[i]);
			if(i!=n-1)
			printf(" ");
		}
	}
	else
	{
		pointer=0; postorder(root2);
		printf("YES\n");
		for(int i=0;i<n;i++)
		{
			printf("%d",post[i]);
			if(i!=n-1)
			printf(" ");
		}
	}
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值