PAT 1043

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
using namespace std;

struct Node
{
	Node* lchild;
	Node* rchild;
	int data;
};
void insert(Node* &root,int data)
{
	if(root==NULL)
	{
		root=new Node;
		root->lchild=NULL;
		root->rchild=NULL;
		root->data=data;
		return;
	}
	if(data<root->data)
		insert(root->lchild,data);
	else 
		insert(root->rchild,data);
}//建树

vector<int> temp,pre,post,prem,postm;

void preorder(Node* root,vector<int> &pre)
{
	if(root==NULL)
		return;
	pre.push_back(root->data);
	preorder(root->lchild,pre);
	preorder(root->rchild,pre);
}
void postorder(Node* root,vector<int> &post)
{
	if(root==NULL)
		return;
	postorder(root->lchild,post);
	postorder(root->rchild,post);
	post.push_back(root->data);
}
void premorder(Node* root,vector<int> &prem)
{
	if(root==NULL)
		return;
	prem.push_back(root->data);
	premorder(root->rchild,prem);
	premorder(root->lchild,prem);
}
void postmorder(Node* root,vector<int> &postm)
{
	if(root==NULL)
		return;
	postmorder(root->rchild,postm);
	postmorder(root->lchild,postm);
	postm.push_back(root->data);
}
int main()
{
	int n,k;
	scanf("%d",&n);
	Node* root=NULL;

	for(int i=0;i<n;i++)
	{
		scanf("%d",&k);
		insert(root,k);
		temp.push_back(k);
	}
	preorder(root,pre);
	premorder(root,prem);

	if(temp==pre)
	{
		printf("YES\n");
		postorder(root,post);
		for(int i=0;i<post.size();i++)
		{
			printf("%d",post[i]);
			if(i!=post.size()-1)
			{
				printf(" ");
			}
		}
	}
	else if(temp==prem)
	{
		printf("YES\n");
		postmorder(root,postm);
		for(int i=0;i<postm.size();i++)
		{
			printf("%d",postm[i]);
			if(i!=postm.size()-1)
			{
				printf(" ");
			}
		}
	}
	else 
		printf("NO\n");
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值