G:Tree Recovery POJ 2255 http://poj.org/problem?id=2255
-
总时间限制:
- 1000ms 内存限制:
- 65536kB
-
描述
-
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!
输入
-
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.
输出
- For each test case, recover Valentine's binary tree and print one line containing the tree's postorder traversal (left subtree, right subtree, root). 样例输入
-
DBACEGF ABCDEFG BCAD CBAD
样例输出
-
ACBFGED CDAB
来源
- Ulm Local 1997
AC 代码
#include <iostream>
#include<cstdio>
using namespace std;
struct node{
char data;//存放该节点的值
node* lchild;
node* rchild;
};
void PostOrder(node* root){//后根遍历
if(root->lchild!=NULL){
PostOrder(root->lchild);
}
if(root->rchild!=NULL){
PostOrder(root->rchild);
}
printf("%c",root->data);
}
node* Creat(string preorder,string inorder){//传进来两个参数,分别是先根序列、中根序列
node* root=NULL;//创建根节点,一定要初始化为NULL,不然会报错 Process exited with return value 3221225725
if(preorder.size()>0){
root=new node;
root->data=preorder[0];//初始化根节点的值
root->lchild=NULL;
root->rchild=NULL;
string pre1,pre2;//根据根节点划分的两个先根序列
string in1,in2;//根据根节点划分的两个中根序列
//寻找根结点在中序遍历中的位置
int index=inorder.find(preorder[0]);
//注意substr的用法,第二个参数是子字符串长度
pre1=preorder.substr(1,index);//除去0位置的根节点,1~index为左先根序列
pre2=preorder.substr(index+1,preorder.size()-index-1);//index到序列末尾为右先根序列
in1=inorder.substr(0,index);//以根节点为界,左序列为左中根序列
in2=inorder.substr(index+1,inorder.size()-index-1);//以根节点为界,右序列为右中根序列
root->lchild=Creat(pre1,in1);//重建左子树
root->rchild=Creat(pre2,in2);//重建右子树
}
return root;
}
int main(int argc, char** argv) {
string s1,s2;
while(cin>>s1>>s2){
node*t=Creat(s1,s2);
PostOrder(t);
cout<<endl;
}
return 0;
}