题意:给出一棵二叉树的前序遍历和中序遍历,输出这棵树的后序遍历。
分析:根据前序和中序遍历建树,再后续输出即可,重点在于建树的过程。
//116K 0MS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 30
typedef struct node
{
char c ;
node *left , *right ;
}*tree;
char pre[MAX] , in[MAX] ;
int Find_Index ( char c )
{
int index ;
index = -1 ;
int i ;
for ( i = 0 ; in[i] ; i ++ )
{
if ( in[i] == c )
{
index = i ;
break ;
}
}
return index ;
}
tree BuildTree ( int l_pre , int l_in , int len )
{
tree temp ;
temp = NULL ;
if ( len > 0 )
{
temp = ( tree ) malloc ( sizeof ( node ) ) ;
int k ;
k = Find_Index ( pre[l_pre] ) ;
temp->c = pre[l_pre] ;
temp->left = BuildTree(l_pre+1, l_in, k-l_in);
temp->right = BuildTree(l_pre+1+k-l_in, k+1, len-(k-l_in)-1);
}
return temp ;
}
void Print_Tree ( tree t )
{
if ( t )
{
Print_Tree ( t->left ) ;
Print_Tree ( t->right ) ;
putchar (t->c) ;
}
}
int
main ( )
{
while ( 2 == scanf ("%s%s" , pre , in ) )
{
tree T ;
T = BuildTree ( 0 , 0 , strlen ( pre ) ) ;
Print_Tree ( T ) ;
printf ("\n") ;
free ( T ) ;
}
return 0 ;
}