您的位置:首页 > 大数据 > 人工智能

poj 2255 Tree Recovery

2011-07-28 16:35 337 查看
DescriptionLittle 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!

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

OutputFor each test case, recover Valentine's binary tree and print one line containing the tree's postorder traversal (left subtree, right subtree, root). Sample InputDBACEGF ABCDEFG
BCAD CBAD
Sample OutputACBFGED
CDAB
 
这是一道由先序序列和中序序列求后序序列的题~
大致思想很简单~不用去建树~取先序序列中第一位在中序序列的位置~
再取两序列该位置左右的字符串~依次递归~ 
做完这题我最大的感触就是~字符串的题~还是c++比较好用~#include"string"
#include"iostream"
using namespace std;
int n;
string post;
int Getpoststr(string s1,string s2)
{

int q;
int m;
q=s2.size();
if(q==0)
return 0;
else
{
post.insert((string::size_type)0,1,s1[0]);
m=s2.find(s1[0]);
Getpoststr(s1.substr(m+1,q-m-1),s2.substr(m+1,q-m-1));求右边的子串~
Getpoststr(s1.substr(1,m),s2.substr(0,m));求左边的子串~
}
}

int main()
{
string pre;
string in;
int n;
while(cin >> pre >> in)
{
post.clear();
Getpoststr(pre,in);
cout << post<<endl;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息