ZOJ1944(Tree Recovery)

Tree Recovery

Time Limit: 1 Second      Memory Limit: 32768 KB

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

 1//2009-05-18 18:28:16        Accepted      1944      C++      0      184      Xredman
 2#include <iostream>
 3#include <string>
 4using namespace std;
 5
 6
 7struct node
 8{
 9    char data;
10    node *lchild, *rchild;
11}
;
12
13
14int len;
15
16node *recover(string pre_order, string in_order)
17{
18    node *root;
19    int loc;
20    if(pre_order.length() == 0)
21        root = NULL;
22    else
23    {
24        root = new node;
25        root->data = pre_order[0];
26        loc = in_order.find(root->data);
27
28        root->lchild = recover(pre_order.substr(1, loc), in_order.substr(0, loc));
29        root->rchild = recover(pre_order.substr(loc + 1), in_order.substr(loc + 1));
30    }

31    return root;
32}

33
34void dfs(node *root)
35{
36    if(root)
37    {
38        dfs(root->lchild);
39        dfs(root->rchild);
40        printf("%c", root->data);
41        
42    }

43}

44
45int main()
46{
47    node *root;
48    string pre_order, in_order;
49
50    while(cin>>pre_order>>in_order)
51    {
52        root = recover(pre_order, in_order);
53        dfs(root);
54        putchar('\n');
55    }

56    return 0;
57}

58
59

posted on 2009-05-18 18:31  Xredman  阅读(394)  评论(0编辑  收藏  举报

导航