PAT 1043【BST与二叉树】

考察:
1.二叉树的建树
2.前序遍历,后序遍历
3.BST的特性


这题的思路:
告诉你数组是先序遍历的,so 根已经知道了(数组首位元素),那么按照BST,建一下树(要两次,另外一次是镜像的);
跑一跑先序遍历,对一对是不是呀?
然后是的话就输出后序遍历的方式。

THAT'S ALL;

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

const int N=1e3+10;

struct BST{
	BST* Left;
	BST* Right;
	int w;
};

BST* Insert1(BST* p,int w)
{
	if(p==NULL)
	{
		p=(BST*)malloc(sizeof(BST));
		p->w=w;
		p->Left=NULL;
		p->Right=NULL;
		return p;
	}
	if(w>=p->w)
		p->Right=Insert1(p->Right,w);
	else
		p->Left=Insert1(p->Left,w);
	return p;
}

BST* Insert2(BST* p,int w)
{
	if(p==NULL)
	{
		p=(BST*)malloc(sizeof(BST));
		p->w=w;
		p->Left=NULL;
		p->Right=NULL;
		return p;
	}
	if(w<p->w)
		p->Right=Insert2(p->Right,w);
	else
		p->Left=Insert2(p->Left,w);
	return p;
}

vector<int>xs;
void Preorder(BST* p)
{
	if(p==NULL) return;
	xs.push_back(p->w);
	Preorder(p->Left);
	Preorder(p->Right);
}


void Postorder(BST* p)
{
	if(p==NULL) return;
	Postorder(p->Left);
	Postorder(p->Right);
	xs.push_back(p->w);
}

int main()
{
	int n;
	int a[N];
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
	bool f1=true,f2=true;
	BST* root;
	root=(BST*)malloc(sizeof(BST));
	root->w=a[1];
	root->Left=NULL;
	root->Right=NULL;
	for(int i=2;i<=n;i++)
		Insert1(root,a[i]);
	xs.clear();
	Preorder(root);
	for(int i=0;i<n;i++)
		if(a[i+1]!=xs[i])
		{
			f1=false;
			break;
		}
	if(!f1)
	{
		root=(BST*)malloc(sizeof(BST));
		root->w=a[1];
		root->Left=NULL;
		root->Right=NULL;
		for(int i=2;i<=n;i++)
			Insert2(root,a[i]);
		xs.clear();
		Preorder(root);
		for(int i=0;i<n;i++)
			if(a[i+1]!=xs[i])
			{
				f2=false;
				break;
			}
	}
	if(!f1&&!f2)
	{
		puts("NO");
		return 0;
	}
	puts("YES");
	xs.clear();
	Postorder(root);
	for(int i=0;i<n;i++)
	{
		if(i) printf(" ");
		printf("%d",xs[i]);
	}
	return 0;
}






  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值