中序:BFDAEGC
后序:FDBGECA
后序遍历是先访问右节点,然后访问左节点,最后访问根节点
中序遍历是先访问左节点,然后访问根节点,最后访问右节点
可以知道后序输出中的最后一个字符A即为该二叉树的根节点,然后在中序遍历中找到该节点A的位置,其左边BFD为A的左子树,其右边EGC为A的右子树
在中序中找到A左子树节点的个数和右子树节点的个数,将后序中相同个数进行左右匹配,然后递归处理左子树和右子树
#include<iostream>
#include<string.h>
using namespace std;
typedef struct Tree
{
char x;
struct Tree *left;
struct Tree *right;
}tree;
tree *creat(char *zhong,char *hou,int n)
{
tree *b;
if(n<=0)return NULL;
b=new tree;
b->x =*(hou+n-1);//当前根节点
char *p;
for(p=zhong;p<zhong+n;p++)
{
if(*p==b->x )
break;
} //在中序序列中找到该根节点
int num_zuo=p-zhong; //其左子树节点个数
int num_you=n-num_zuo-1; //其右子树节点个数
b->left =creat(zhong,hou,num_zuo); //左子树
b->right =creat(zhong+num_zuo+1,hou+num_zuo,num_you); //右子树 ,因为中序列中要跳过根节点,所以+1
return b;
}
void print(tree *p)
{
if(p==NULL)return;
else
{
cout<<p->x ;
print(p->left );
print(p->right );
}
}
int main()
{
char zhong[1000];
char hou[1000];
cin>>zhong>>hou;
tree *t=creat(zhong,hou,strlen(zhong));
print(t);
return 0;
}