【编程之美】3.9已知先序和中序遍历,求后序遍历+POJ-2255

来源:互联网 发布:土巴兔云设计软件 编辑:程序博客网 时间:2024/05/21 17:40

很久以前写过,现在把我的递归版本代码贴出

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;}


原创粉丝点击