原题链接:http://poj.org/problem?id=2255
Tree Recovery
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 17320 Accepted: 10634
Description
Little Valentine liked playing with binary trees very much. Her favorite game was constructing randomly looking binary trees with capital letters in the nodes.
This is an example of one of her creations:
D
/ \
/ \
B E
/ \ \
/ \ \
A C G
/
/
F
To record her trees for future generations, she wrote down two strings for each tree: a preorder traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree). For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG.
She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried it).
Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed possible, but only because she never had used the same letter twice in the same tree.
However, doing the reconstruction by hand, soon turned out to be tedious.
So now she asks you to write a program that does the job for her!
Input
The input will contain one or more test cases.
Each test case consists of one line containing two strings preord and inord, representing the preorder traversal and inorder traversal of a binary tree. Both strings consist of unique capital letters. (Thus they are not longer than 26 characters.)
Input is terminated by end of file.
Output
For each test case, recover Valentine’s binary tree and print one line containing the tree’s postorder traversal (left subtree, right subtree, root).
Sample Input
DBACEGF ABCDEFG
BCAD CBAD
Sample Output
ACBFGED
CDAB
Source
Ulm Local 1997
题解:这个题思路蛮简单清晰的,已知树的先序和中序遍历序列,求该树的后序遍历序列。
这个题是以先序遍历序列为主,对中序序列进行分割,从先序遍历序列中找到的第一个点就是当前树的根节点,然后在中序遍历中找到这个点,该点的左侧就是左子树,右侧就是右子树,一直递归即可。
虽然思路很清楚,但是写的时候无从下手,有两种方法,就是建树和不建树。如果建树就需要根据两个遍历序列先建树,再进行后序遍历;如果不建树,可以采用下标访问,但是问题在于这不一定是一棵完全二叉树,所以我们无法保证下标关系前提下输出序列是否正确,所以可以采用指针的做法。
我的代码:
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
void find(char *a,char *b,char *c,int len)
{
if(len==0)
{
return;
}
int pos = strchr(b,a[0])-b;
//strchr()是C标准库函数,返回的是a[0]在字符串b中的位置
int left = pos ;
int right = len - pos -1;
find(a+1,b,c,left);
find(a+left+1,b+left+1,c+left,right);
c[len-1]=a[0];
}
int main()
{
char pre[27];
char mid[27];
char end[27];
while(~scanf("%s %s",pre,mid))
{
memset(end,0,sizeof(end));
int len = strlen(pre);
find(pre,mid,end,len);
end[len]='\0';
puts(end);
}
}
下面分享一个建树的做法
https://blog.csdn.net/u013068502/article/details/47183545