Problem Description
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
Input
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
第二行输入二叉树的中序遍历序列。
Output
输出该二叉树的后序遍历序列。
Example Input
ABDCEF BDAECF
Example Output
DBEFCA
Hint
Author
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
struct node *lchild,*rchild;
};
int search(char t[],char ch)
{
int i,l;
l=strlen(t);
for(i=0;i<l;i++)
{
if(t[i]==ch)
return i;
}
return 0;
}
struct node *creat(char s[],char t[],int ps,int in,int n)
{
int k;struct node *root;
if(n<=0)
root=NULL;
else
{
k=search(t,s[ps]);
if(k==-1)
root=NULL;
else
{
root=(struct node *)malloc(sizeof(struct node));
root->data=s[ps];
if(k==in)
root->lchild=NULL;
else
root->lchild=creat(s,t,ps+1,in,k-in);
if(k==in+n-1)
root->rchild=NULL;
else
root->rchild=creat(s,t,ps+1+(k-in),k+1,n-(k-in)-1);
}
}
return root;
}
void lastprint(struct node *root)
{
if(root)
{
lastprint(root->lchild);
lastprint(root->rchild);
printf("%c",root->data);
}
}
int main()
{
struct node *root;
char s[102],t[102];
int n;
scanf("%s",s);
scanf("%s",t);
n=strlen(s);
root=creat(s,t,0,0,n);
lastprint(root);
printf("\n");
return 0;
}
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
struct node *lchild,*rchild;
};
int search(char t[],char ch)
{
int i,l;
l=strlen(t);
for(i=0;i<l;i++)
{
if(t[i]==ch)
return i;
}
return 0;
}
struct node *creat(char s[],char t[],int ps,int in,int n)
{
int k;struct node *root;
if(n<=0)
root=NULL;
else
{
k=search(t,s[ps]);
if(k==-1)
root=NULL;
else
{
root=(struct node *)malloc(sizeof(struct node));
root->data=s[ps];
if(k==in)
root->lchild=NULL;
else
root->lchild=creat(s,t,ps+1,in,k-in);
if(k==in+n-1)
root->rchild=NULL;
else
root->rchild=creat(s,t,ps+1+(k-in),k+1,n-(k-in)-1);
}
}
return root;
}
void lastprint(struct node *root)
{
if(root)
{
lastprint(root->lchild);
lastprint(root->rchild);
printf("%c",root->data);
}
}
int main()
{
struct node *root;
char s[102],t[102];
int n;
scanf("%s",s);
scanf("%s",t);
n=strlen(s);
root=creat(s,t,0,0,n);
lastprint(root);
printf("\n");
return 0;
}
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
struct node *lchild,*rchild;
};
int search(char t[],char ch)
{
int i,l;
l=strlen(t);
for(i=0;i<l;i++)
{
if(t[i]==ch)
return i;
}
return 0;
}
struct node *creat(char s[],char t[],int ps,int in,int n)
{
int k;struct node *root;
if(n<=0)
root=NULL;
else
{
k=search(t,s[ps]);
if(k==-1)
root=NULL;
else
{
root=(struct node *)malloc(sizeof(struct node));
root->data=s[ps];
if(k==in)
root->lchild=NULL;
else
root->lchild=creat(s,t,ps+1,in,k-in);
if(k==in+n-1)
root->rchild=NULL;
else
root->rchild=creat(s,t,ps+1+(k-in),k+1,n-(k-in)-1);
}
}
return root;
}
void lastprint(struct node *root)
{
if(root)
{
lastprint(root->lchild);
lastprint(root->rchild);
printf("%c",root->data);
}
}
int main()
{
struct node *root;
char s[102],t[102];
int n;
scanf("%s",s);
scanf("%s",t);
n=strlen(s);
root=creat(s,t,0,0,n);
lastprint(root);
printf("\n");
return 0;
}