分析 :根据二叉树的前序和中序建树,输出后序。
#include <iostream>
#include <cstring>
#include <vector>
#include <stdio.h>
#include <queue>
#include <math.h>
#include <stack>
#include <algorithm>
#include <map>
#include <set>
#include <iostream>
using namespace std;
#define MAX 999999999
typedef long long ll;
int n, m, k;
int pre[ 31 ] , in[ 31 ] ;
int numpre, numin;
struct Node{
Node* left;
Node* right;
int data;
} ;
Node * create ( Node* root, int prel, int prer, int inl, int inr)
{
if ( prel > prer) return NULL ;
if ( root == NULL ) {
root = ( Node* ) malloc ( sizeof ( Node) ) ;
root- > data = pre[ prel] ;
root- > left = NULL ;
root- > right = NULL ;
}
int k ;
for ( int i = inl; i<= inr ; i++ )
{
if ( in[ i] == pre[ prel] )
{
k = i; break ;
}
}
int num = k - inl;
root- > left = create ( root- > left, prel + 1 , prel + num, inl, k - 1 ) ;
root- > right = create ( root- > right, prel + 1 + num, prer, k + 1 , inr) ;
return root;
}
int f ;
void postT ( Node * root)
{
if ( root == NULL ) return ;
postT ( root- > left) ;
postT ( root- > right) ;
if ( f == 0 ) {
f = 1 ;
cout<< root- > data;
}
else
cout<< " " << root- > data;
}
int main ( )
{
cin>> n;
stack< int > s;
for ( int i = 0 ; i < 2 * n; i++ )
{
string st;
cin>> st;
if ( st == "Push" ) {
int x; cin>> x;
s. push ( x) ;
pre[ numpre++ ] = x;
}
else {
in[ numin++ ] = s. top ( ) ;
s. pop ( ) ;
}
}
Node* root = NULL ;
root = create ( root, 0 , n- 1 , 0 , n- 1 ) ;
postT ( root) ;
return 0 ;
}