刨芋吧 关注:37贴子:4,821
  • 2回复贴,共1

2255:重建二叉树

只看楼主收藏回复

总时间限制: 1000ms 内存限制: 65536kB
描述
给定一棵二叉树的前序遍历和中序遍历的结果,求其后序遍历。
输入
输入可能有多组,以EOF结束。
每组输入包含两个字符串,分别为树的前序遍历和中序遍历。每个字符串中只包含大写字母且互不重复。
输出
对于每组输入,用一行来输出它后序遍历结果。
样例输入
DBACEGF ABCDEFG
BCAD CBAD
样例输出
ACBFGED
CDAB
提示
以英文题面为准


1楼2013-05-06 22:47回复
    2255:Tree Recovery
    查看
    提交
    统计
    提示
    提问
    总时间限制: 1000ms 内存限制: 65536kB
    描述
    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!
    输入
    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.
    输出
    For each test case, recover Valentine's binary tree and print one line containing the tree's postorder traversal (left subtree, right subtree, root).
    样例输入
    DBACEGF ABCDEFG
    BCAD CBAD
    样例输出
    ACBFGED
    CDAB


    2楼2013-05-06 22:51
    回复
      #include<stdio.h>
      #include<string.h>
      void recover (char * f, char * m, int l) {
      if (l==0) return;
      if (l==1) {
      printf ("%c", f[0]);
      return;
      }
      int i=0;
      if (m[0]==f[0]) {
      recover (f+1, m+1, l-1);
      printf ("%c", f[0]);
      return;
      }
      while (m[i]!=f[0]) i++;
      recover (f+1, m, i);
      recover (f+i+1, m+i+1, l-i-1);
      printf ("%c", f[0]);
      }
      int main ()
      {
      char f[1000], m[1000];
      int l;
      while (scanf ("%s", f)!=EOF) {
      scanf ("%s", m);
      l=strlen(f);
      recover (f, m, l);
      printf("\n");
      }
      return 0;
      }


      3楼2013-05-06 23:32
      回复