您的位置:首页 > 理论基础 > 数据结构算法

数据结构OJ作业 二叉树

2017-04-22 23:03 162 查看
题目传送门: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 二叉树