UVa 536 - Tree Recovery 前中序求后序

来源:互联网 发布:苹果mac用户名怎么改 编辑:程序博客网 时间:2024/06/07 07:16


Tree Recovery

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 isABCDEFG.

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 Specification

The input file 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 Specification

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 <iostream>#include <cstdio>#include <cstring>using namespace std;const int MAX = 26+4;struct Node{char elem;struct Node *left;struct Node *right;};void aftOrder(char *in, char *pre, int length){if(length==0)return ;Node node;node.elem = *pre;int rootIndex = 0;for(;rootIndex<length; rootIndex++){if(in[rootIndex]== *pre)break;}aftOrder(in, pre+1, rootIndex);// 左子树aftOrder(in+rootIndex+1, pre+rootIndex+1,length-(rootIndex+1));// 右子树cout << node.elem;// 输出rootreturn ;}int main(){//freopen("in.txt","r",stdin);char pre[MAX], in[MAX];while(cin>>pre){cin>>in;aftOrder(in, pre, strlen(pre));cout << endl;memset(pre, '\0', sizeof(pre));memset(in, '\0', sizeof(in));}return 0;}


 

0 0
原创粉丝点击