很久以前写过,现在把我的递归版本代码贴出
struct tree
{
char c;
struct tree * left_child;
struct tree * right_child;
} * root;
tree * create_tree(char pre[], char in[], int len)
{
if (len == 0) return NULL;
tree * t = new tree;
t->c = pre[0];
int i;
for (i = 0; i < len; ++i)
if (in[i] == pre[0])
break;
int j;
t->left_child = create_tree(pre + 1, in, i);
t->right_child = create_tree(pre + i + 1, in + i + 1, len - i - 1);
return t;
}
void print(tree * t) {
if (t == NULL) return ;
print(t->left_child);
print(t->right_child);
cout<<t->c;
}
int main()
{
char pre[30], in[30];
root = new tree;
while (scanf("%s%s", pre, in) == 2) {
root = create_tree(pre, in, strlen(pre));
print(root);
printf("\n");
}
return 0;
}