【输入】
第一行为前序遍历,第二行为中序遍历。 二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
FDXEAG
XDEFAG
【输出】
后序遍历的字符串。
XEDGAF
【图解】
1.找到前序遍历字符串(pre)第一个F,对应到中序遍历字符串(in)相应位置
2.通过in划分左右子树
3.对应到pre
4.递归
#include <iostream>
#include <stdlib.h>
using namespace std;
string pre,in;
typedef struct tree{
char key;
struct tree* left;
struct tree* right;
}tree;
tree* build_tree(string pre,string in,int n)
{
string l_pre="",r_pre="";
string l_in="",r_in="";
int l_pre_len=0,r_pre_len=0;
int l_in_len=0,r_in_len=0;
if(n==0) return NULL;
tree *t=(tree*)malloc(sizeof(tree));
t->key=pre[0];
for(int i=0;i<n;++i){
if(i<=l_in_len&&in[i]!=pre[0]){
l_in+=in[i];
l_in_len++;
}
else if(in[i]!=pre[0]){
r_in+=in[i];
r_in_len++;
}
}
for(int i=1;i<n;++i){
if(i<=l_in_len){
l_pre+=pre[i];
}
else{
r_pre+=pre[i];
}
}
t->left=build_tree(l_pre,l_in,l_in_len);
t->right=build_tree(r_pre,r_in,r_in_len);
return t;
}
void postOrder(tree*t){
if(t->left) postOrder(t->left);
if(t->right) postOrder(t->right);
cout<<t->key;
}
int main(void){
cin>>pre>>in;
int len=pre.length();
tree* root=NULL;
root=build_tree(pre,in,pre.length());
postOrder(root);
return 0;
}