http://acm.nyist.net/JudgeOnline/problem.php?pid=221

已知一棵树的先序和中序遍历,求该树的后序遍历,,,

例如:

DBACEGF ABCDEFG

ACBFGED

AC代码:

#include<stdio.h>
#include<string.h>
void build(int n,char *s1,char *s2)//构造后序遍历过程
{
	if(n<=0) return;
	int p=strchr(s2,s1[0])-s2;
	build(p,s1+1,s2);//访问左子树
	build(n-p-1,s1+p+1,s2+p+1);//访问右子树
	printf("%c",s1[0]);
}
int main()
{
	char a[27],b[27];
	while(scanf("%s%s",a,b)==2)
	{
		int n=strlen(a);
		build(n,a,b);
		printf("\n");
	}return 0;
}

法二:

 
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
typedef struct str
{
	char date;
	struct str *l,*r;
}*Tire,T;
Tire build(string s,string s1)
{    
	   Tire u=NULL;
	   if(s.size()>0)
	   {
		u=new T;
		u->date=s[0];
		int k=s1.find(s[0]);
		u->l=build(s.substr(1,k),s1.substr(0,k));
		u->r=build(s.substr(k+1),s1.substr(k+1));
	    }
	  return u;
}
void delet(Tire root)
{
	if(root->l) delet(root->l);
	if(root->r) delet(root->r);
	delete root;
}
void postorder(Tire root)
{
	if(root->l) postorder(root->l);
	if(root->r) postorder(root->r);
	cout<<root->date;
}
int main()
{
	string a,b;
	while(cin>>a>>b)
	{
		Tire root=build(a,b);
		postorder(root);
		cout<<endl;
		delet(root);
	}return 0;
}        



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值