http://poj.org/problem?id=2255
方法:
根据preorder和inorder构造postorder
例如preorder:DBACEGF inorder:ABCDEFG
D
/ \
/ \
B E
/ \ \
/ \ \
A C G
/
/
F
preorder的第一个节点D就是这棵树的根节点,即为postorder中的最后一个元素
然后在inorder中找到该节点D,其左边为ABC为该根节点左子树的inorder,右边EFG为右子树inorder
对应的preorder中BAC为该根节点左子树的perorder,EGF为右子树preorder
再递归对左右子树应用同样的方法
Description
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:
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: #include <iostream>
2: #include <string>
3: #include <fstream>
4:
5: using namespace std ;
6:
7: //end=n-1,为postorder中的最后一个元素(root)的位置
8: void GetPostorder(const string& preStr, const string& inStr,string& postStr,int end)
9: {
10: if(preStr=="")
11: return ;
12:
13: postStr[end] = preStr[0] ;
14: string::size_type rootPos = inStr.find(preStr[0]);
15: size_t leftLen = rootPos ;
16: size_t rightLen = preStr.size()-rootPos-1 ; //****注意不是end-rootPos,因为end对应的是postStr
17:
18: //right subtree
19: GetPostorder(preStr.substr(1+leftLen),inStr.substr(rootPos+1),postStr,end-1);
20: //left substree
21: GetPostorder(preStr.substr(1,leftLen),inStr.substr(0,leftLen),postStr,end-rightLen-1);
22: }
23:
24: void run2255()
25: {
26: ifstream in("in.txt");
27:
28: string preStr,inStr ;
29: size_t len ;
30: while(in>>preStr>>inStr)
31: {
32: len = preStr.size();
33: string postStr(len,'0');
34: GetPostorder(preStr,inStr,postStr,len-1);
35: cout<<postStr<<endl;
36: }
37: }