POJ-2255 Tree Recovery

来源:互联网 发布:js input 光标颜色 编辑:程序博客网 时间:2024/06/14 00:39

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 ABCDEFGBCAD CBAD
Sample Output
ACBFGEDCDAB

  前序+中序—>后序

  后序+中序—>前序

  前序+后序  结果不唯一,别问我为什么,我也不知道大笑

#include<stdio.h>#include<string.h>char sa[100],sb[100],ans[100];void build(int l,char *sa,char *sb,char *s){    if(l<=0)return;    int p=strchr(sb,sa[0])-sb;//找到根节点在中序遍历中的位置    build(p,sa+1,sb,s);//构造左子树的后序遍历,递归查下一个字符在中序便利中的位置    build(l-p-1,sa+p+1,sb+p+1,s+p);//构造右子树的后序遍历,道理同上。    s[l-1]=sa[0];//把根节点添加到最后}int main(){    while(~scanf("%s%s",sa,sb))    {       int l=strlen(sa);       build(l,sa,sb,ans);       ans[l]='\0';       printf("%s\n",ans);    }    return 0;}