Tree Recovery

来源:互联网 发布:弹奏音乐的软件 编辑:程序博客网 时间:2024/05/23 18:04

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 ABCDEFGBCAD CBAD

Sample Output

ACBFGEDCDAB

本想找规律直接输出后序序列,无奈功力尚浅,还是老老实实建树再遍历。

#include <iostream>#include<cstring>#include<cstdlib>using namespace std;struct Node{    char ch;    Node *rnode,*lnode;};typedef Node* Tree;char pre[30],in[30];Tree BuildTree(char *pre,char *in,int n);void PostTraverse(Tree t);int main(){    while(cin>>pre>>in){        int len=strlen(pre);        Tree t;        t=BuildTree(pre,in,len);        PostTraverse(t);        cout<<endl;    }    return 0;}Tree BuildTree(char *pre,char *in,int n){    Tree root;    char *p,*q;    int i;    if(n<=0) return NULL;    root=(Tree)malloc(sizeof(Node));    root->ch=pre[0];    root->lnode=root->rnode=NULL;    i=0;    while(i<n){        if(pre[0]==in[i]) break;        ++i;    }    p=pre+1;    q=in;    root->lnode=BuildTree(p,q,i);    p=pre+i+1;    q=in+i+1;    root->rnode=BuildTree(p,q,n-i-1);    return root;}void PostTraverse(Tree t){    if(t){        PostTraverse(t->lnode);        PostTraverse(t->rnode);        cout<<t->ch;    }}



0 0
原创粉丝点击