已知一棵树的先序和中序遍历,求该树的后序遍历,,,
例如:
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;
}
本文介绍了一种通过已知树的先序和中序遍历来推导出其后序遍历的方法,并提供了两种实现算法。其中包括一个简单的递归算法和一个更复杂但更为通用的树构建算法。

被折叠的 条评论
为什么被折叠?



