http://acm.nyist.net/JudgeOnline/problem.php?pid=221
1、前序遍历的第一个节点是根节点。
2、在中序遍历中找到这个根节点,然后把中序遍历的字符串分成了左串和右串,也就是该根节点的左子树和右子树。
3、递归下去就可以了,递归的出口就是root后面的节点个数小于等于0.
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAX = 27;
char pre[MAX], in[MAX];
struct Node {
Node(char c) {
date = c;
left = right = NULL;
}
Node *left, *right;
char date;
};
void rebuild(Node *&root, char *pre, char *in, int len) {
if (len >= 1) {
char rc = pre[0];
root = new Node(rc);
int pos;
for (int i = 0; i < len; i++)
if (in[i] == rc) {
pos = i;
break;
}
int leftSubLen = pos;
int RightSubLen = len - pos - 1;
rebuild(root->left, pre+1, in, leftSubLen);
rebuild(root->right, pre+leftSubLen+1, in+pos+1, RightSubLen);
}
}
void postTraverse(Node *root) {
if (root) {
postTraverse(root -> left);
postTraverse(root -> right);
cout << root -> date;
}
}
int main() {
Node *root;
while (scanf ("%s%s", pre, in) != EOF) {
rebuild(root, pre, in, strlen(pre));
postTraverse(root);
cout << endl;
}
}