您的位置:首页 > 其它

POJ2255 Tree Recovery 二叉树遍历

2015-08-01 09:34 525 查看
Tree Recovery

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 12523Accepted: 7836
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:

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

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


由前序和中序求后序,应该算是比较好理解的吧,和HDU1710一样,具体的参见那篇博客吧,关于遍历的网上一搜也是一堆。
HDU1710

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;

char pre[30],mid[30],n;

typedef struct Node{
char v;
struct Node *left,*right;
}node;

node* root;

node* newNode(char x){
node* u=(node*)malloc(sizeof(node));
u->left=u->right=NULL;
u->v=x;
return u;
}

node* creat(char *pre,int l1,char *mid,int l2){
int i,j,k;
for(i=0;i<l2;i++)
if(pre[0]==mid[i]) break;
node* u=newNode(mid[i]);
if(i>0)
u->left=creat(pre+1,i,mid,i);
if(i<l2-1)
u->right=creat(pre+i+1,l2-i-1,mid+i+1,l2-i-1);
return u;
}

void remove_tree(node* u){
if(u==NULL) return ;
remove_tree(u->left);
remove_tree(u->right);
delete u;
}

void print(node* u){
if(u==NULL) return ;
print(u->left);
print(u->right);
printf("%c",u->v);
}

int main()
{
int i,j,n;
while(scanf("%s",pre)!=EOF){
scanf("%s",mid);
n=strlen(pre);
remove_tree(root);
root=creat(pre,n,mid,n);
print(root);
printf("\n");
}
return 0;
}


养成释放空间的好习惯。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: