PAT A1119 pre- and post-order traversals(30)

这道题快把我弄晕了。。我讨厌各种序结合建树嘤嘤嘤。。。

先序第一个肯定是根,第二个是左子树或者右子树的根pre[preL] -> 在后序序列找到该点划分左右子树,然后计算个数,递归。(看了一下别人的思路写的)

#include<cstdio>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
	int n;
vector<int> pre,post,in;
bool unq=false;
struct node{
	int sq;
	node* lchild;
	node* rchild;
};
node* create(int preL,int preR,int postL,int postR){
	if(preL>preR){
		unq=true;
		return NULL;
	}
	node* root=new node;
	root->sq=pre[preL];
	if(preL==preR){
		root->lchild=NULL;
		root->rchild=NULL;
		return root;
	}


	int i=preL+1;
	int j=postL;
	if(i<=preR){
		for(j=postL;j<=postR;j++){
			if(pre[i]==post[j]) break;	
		}
	}
		int numleft=j-postL;
		root->lchild=create(i,i+numleft,postL,j);
		root->rchild=create(i+numleft+1,preR,j+1,postR-1);
	return root;
}

void inorder(node* root){
	if(root->lchild!=NULL) inorder(root->lchild);
	in.push_back(root->sq);
	if(root->rchild!=NULL) inorder(root->rchild);
}
int main(){
	scanf("%d",&n);
	int i,temp;
	for(i=0;i<n;i++){
		scanf("%d",&temp);
		pre.push_back(temp);
	}
	for(i=0;i<n;i++){
		scanf("%d",&temp);
		post.push_back(temp);
	}
	node* root=create(0,n-1,0,n-1);
	inorder(root);
	if(unq==true) printf("No\n");
	else printf("Yes\n");
	for(i=0;i<n;i++){
		if(i<n-1) printf("%d ",in[i]);
		else printf("%d\n",in[i]);
	}
	system("pause");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值