Tree Recovery
Tree Recovery |
Little Valentine liked playing with binary trees very much. Her favoritegame was constructingrandomly 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 stringsfor each tree: a preordertraversal (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 theinorder traversal is ABCDEFG.
She thought that such a pair of strings would give enough information toreconstruct the tree later (but she never tried it).
Now, years later, looking again at the strings, she realized thatreconstructing the trees was indeedpossible, but only because she never had used the same letter twicein 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 andinord, representing thepreorder traversal and inorder traversal of a binary tree. Both stringsconsist of unique capitalletters. (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 linecontaining the tree's postordertraversal (left subtree, right subtree, root).Sample Input
DBACEGF ABCDEFG BCAD CBAD
Sample Output
ACBFGED CDAB
DBACEGF ABCDEFG
BAC ABC EGF EFG
AA CC GF FG
FF
#include<iostream>
#include<string>
using namespace std;
///////////////////
class TreeRecovery{
private:
string preord;//前序
string inord;//中序
string postorder;//后序
void reconstruct(string p, string i);
public:
void initial(string p, string i){
preord = p;
inord = i;
postorder.clear();
}
void computing(){reconstruct(preord, inord);}
void outResult(){cout << postorder << endl;}
};
void TreeRecovery::reconstruct(string preord, string inord){
int sz = preord.size();
if(sz > 0){
int p = int(inord.find(preord[0]));
reconstruct(preord.substr(1, p), inord.substr(0, p)); //left subtree
reconstruct(preord.substr(p+1, sz-p-1), inord.substr(p+1, sz-p-1)); //right subtree
postorder.push_back(preord[0]); //root
}
}
/////////////////////
int main(){
TreeRecovery tr;
string p, i;
while(cin >> p >> i){
tr.initial(p, i);
tr.computing();
tr.outResult();
}
return 0;
}
/*
INPUT
DBACEGF ABCDEFG
BCAD CBAD
AB BA
--------------
OUTPUT
ACBFGED
CDAB
BA
*/