已知先序和中序求后序

输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。

Input

第一行输入二叉树的先序遍历序列; 
第二行输入二叉树的中序遍历序列。

Output

输出该二叉树的后序遍历序列。

Sample Input

ABDCEF
BDAECF

Sample Output

DBEFCA

#include
#include
#include
char str1[100],str2[100];
struct node
{
    char data;
    struct node *l,*r;
};
struct node *build(char *str1,char *str2,int s)
{
    int i;
    struct node *root;
    root=(struct node *)malloc(sizeof(struct node));
    if(s<=0)
        return NULL;
    root->data=*str1;
    for(i=0; i     {
        if(str2[i]==*str1)
            break;
    }
    root->l=build(str1+1,str2,i);
    root->r=build(str1+i+1,str2+i+1,s-i-1);
    return root;
}
void last(struct node *root)
{
    if(root!=NULL)
    {
        last(root->l);
        last(root->r);
        printf("%c",root->data);
    }
}
int main()
{
    int st;
    struct node *root;
    scanf("%s",str1);
    scanf("%s",str2);
    st=strlen(str1);
    root=build(str1,str2,st);
    last(root);
    return 0;
}

你可能感兴趣的:(二叉树)