#include<iostream>
#include<string>
#include<fstream>
using namespace std;
//#define DEBUG
static const int MAXNODES = 500;
struct node
{
char c;
node *lc;
node *rc;
};
static struct node nodes[MAXNODES];
static int p = 0;
struct node * create(string in, string pre)
{
struct node *root = NULL;
if (pre.length() > 0)
{
root = &nodes[p++];
root->c = pre[0];
int i = in.find(root->c);
root->lc = create(in.substr(0, i), pre.substr(1, i));
root->rc = create(in.substr(i + 1), pre.substr(i+1));
}
return root;
}
void postorder(struct node* root)
{
if (!root)
return;
postorder(root->lc);
postorder(root->rc);
cout << root->c ;
}
int main()
{
#ifdef DEBUG
fstream cin("G:\\book\\algorithms\\acm\\Debug\\dat.txt");
#endif
string pre, in;
while (cin >> pre >> in)
{
postorder(create(in, pre));
cout << "\n";
}
return 0;
}
采用递归的方法,节点预先分配,可能分配的过多了。
对string 的find()和substr()的掌握。