PAT 1086 Tree Traversals Again
问题简述
给出先序与中序,要求你给出后序遍历的序列
代码-C
其中一个小报错Variably modified array at file scope;在C中数组大小似乎不支持const 类型表示,
那改为宏吧
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxn 50
typedef struct node{
int data;
struct node* lc;
struct node* rc;
} node;
typedef struct Stack
{
int top;
int data[ maxn] ;
} Stack;
Stack st;
void st_init ( )
{
st. top = - 1 ;
memset ( st. data, 0 , maxn) ;
}
void st_push ( int val)
{
st. data[ ++ st. top] = val;
}
void st_pop ( )
{
st. data[ st. top-- ] = 0 ;
}
int st_top ( )
{
return st. data[ st. top] ;
}
int pre[ maxn] , post[ maxn] , in[ maxn] ;
int n, num = 0 ;
node* Create ( int preL, int preR, int inL, int inR)
{
if ( preL > preR)
return NULL ;
node* root = ( node* ) malloc ( sizeof ( node) ) ;
root-> data = pre[ preL] ;
int k;
for ( k = inL; k <= inR; k++ )
{
if ( in[ k] == pre[ preL] )
break ;
}
int numLeft = k - inL;
root-> lc = Create ( preL + 1 , preL + numLeft, inL, k- 1 ) ;
root-> rc = Create ( preL + numLeft + 1 , preR, k + 1 , inR) ;
return root;
}
void postOrder ( node* root)
{
if ( root == NULL )
return ;
postOrder ( root-> lc) ;
postOrder ( root-> rc) ;
printf ( "%d" , root-> data) ;
num++ ;
if ( num < n)
printf ( " " ) ;
}
int main ( )
{
st_init ( ) ;
scanf ( "%d" , & n) ;
char str[ 5 ] ;
int x, preIndex = 0 , inIndex = 0 ;
for ( int i = 0 ; i < 2 * n; i++ )
{
scanf ( "%s" , str) ;
if ( strcmp ( str, "Push" ) == 0 )
{
scanf ( "%d" , & x) ;
pre[ preIndex++ ] = x;
st_push ( x) ;
}
else
{
in[ inIndex++ ] = st_top ( ) ;
st_pop ( ) ;
}
}
node * root = Create ( 0 , n- 1 , 0 , n- 1 ) ;
postOrder ( root) ;
return 0 ;
}