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 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 is terminated by end of file.
DBACEGF ABCDEFG BCAD CBAD
ACBFGED CDAB
#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;// 输出root return ; } 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; }
UVa 536 - Tree Recovery 前中序求后序,布布扣,bubuko.com
UVa 536 - Tree Recovery 前中序求后序
原文:http://blog.csdn.net/china_zoujinyong/article/details/20772523