数据结构OJ作业 二叉树

来源:互联网 发布:南京栖霞网络问政 编辑:程序博客网 时间:2024/06/05 23:01

题目传送门:http://poj.org/problem?id=2255
Tree Recovery
给出一个二叉树的前序和中序,求二叉树的后序。
节约空间,并不实际建树,而是一边搜索一边输出。
同hdoj1710,写完了这篇blog才发现以前也写过,尴尬……
http://blog.csdn.net/jlu_nnbs/article/details/55806227

#include <cstdio>#include <cstring>using namespace std;char pre[30],in[30];void build(int l, int r, int root){    if (l > r) return ;    int loc;    for (int i = l; i <= r; i ++) {        if (pre[root] == in[i]) {            loc = i;            break;        }    }    // 中序左子树根的位置就是当前位置加一    build(l, loc - 1, root + 1);    // 而右子树的根是所有左子树结点遍历完后的第一个    build(loc + 1, r, root + loc - l + 1);    printf("%c",in[loc]);    return ;}int main(){    while (~scanf(" %s %s",pre,in)) {        int len = strlen(pre);        build(0,len - 1,0);        printf("\n");    }    return 0;}
0 0
原创粉丝点击