思路:
根据中序和后序序列建树。 层序遍历该树,若该层flag为1直接打印,否则压入栈中逆序打印,每层flag要取反。
代码实现:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair< int , int > PII;
typedef struct Tnode * p;
const int N= 35 ;
int n, postindex, inorder[ N] , postorder[ N] ;
struct Tnode{
p ls, rs;
int data;
} ;
p root;
int find ( int begin, int end, int val) {
for ( int i= begin; i<= end; i++ ) {
if ( inorder[ i] == val) return i;
}
return - 1 ;
}
p buildtreechild ( int begin, int end) {
if ( begin> end) return NULL ;
p root= new Tnode;
root- > data= postorder[ postindex] ;
int index= find ( begin, end, postorder[ postindex] ) ;
if ( index== - 1 ) return NULL ;
postindex-- ;
root- > rs= buildtreechild ( index+ 1 , end) ;
root- > ls= buildtreechild ( begin, index- 1 ) ;
return root;
}
p buildtree ( ) {
if ( inorder== NULL || postorder== NULL ) return NULL ;
return buildtreechild ( 0 , n- 1 ) ;
}
void levelorder ( p root) {
queue< p> q;
if ( root) q. push ( root) ;
int flag= 0 ;
int first= root- > data;
while ( ! q. empty ( ) ) {
int len= q. size ( ) ;
if ( flag== 1 ) {
for ( int i= 0 ; i< len; i++ ) {
p t= q. front ( ) ;
q. pop ( ) ;
cout<< " " << t- > data;
if ( t- > ls) q. push ( t- > ls) ;
if ( t- > rs) q. push ( t- > rs) ;
}
flag= 0 ;
}
else {
stack< int > s;
for ( int i= 0 ; i< len; i++ ) {
p t= q. front ( ) ;
q. pop ( ) ;
s. push ( t- > data) ;
if ( t- > ls) q. push ( t- > ls) ;
if ( t- > rs) q. push ( t- > rs) ;
}
while ( ! s. empty ( ) ) {
int t= s. top ( ) ;
s. pop ( ) ;
if ( t== first) cout<< t;
else cout<< " " << t;
}
flag= 1 ;
}
}
}
int main ( ) {
scanf ( "%d" , & n) ;
for ( int i= 0 ; i< n; i++ ) scanf ( "%d" , & inorder[ i] ) ;
for ( int i= 0 ; i< n; i++ ) scanf ( "%d" , & postorder[ i] ) ;
postindex= n- 1 ;
root= buildtree ( ) ;
levelorder ( root) ;
return 0 ;
}