前序+后序=〉(二叉)树的个数

假设前序序列为pre,后序序列为post,他们的长度分别为n,必有:
  pre[0]==post[n-1],同时pre[1]为根节点的第一颗子树的根节点,再post中查找pre[1],这样就可以判定出该树的第一颗子树的前序序列和后序序列。同样的道理,可以判断出该树的所有子树的前序和后序序列。递归解之。代码如下:

 

#include  < iostream >
#include 
< string >
using   namespace  std;

long  process( int  m,  string  pre,  string  post)
{
    
if  (pre.substr( 0 , 1 !=  post.substr(post.length() - 1 , 1 ))
        
return   0 ;
    
if  (pre.length()  ==   1 )
        
return   1 ;
    
long  ans  =   1 ;
    pre 
=  pre.substr( 1 , pre.length());
    post 
=  post.substr( 0 , post.length() - 1 );
    
int  numchild  =   0 ;
    
long  comb  =   1 ;
    
while  (pre.length()  >   0 ) {
        numchild
++ ;
        
int  index  =  post.find(pre[ 0 ]);
        
string  newPost  =  post.substr( 0 , index + 1 );
        post 
=  post.substr(index + 1 , post.length());
        
string  newPre  =  pre.substr( 0 , index + 1 );
        pre 
=  pre.substr(index + 1 , pre.length());
        ans 
*=  process(m, newPre, newPost);
        
if  (ans  ==   0 )
            
return   0 ;
        comb 
=  comb * (m - numchild + 1 ) / numchild;
    }
    
return  ans * comb;
}


int  main()
{
    
string  post, pre;
    
int   m;

    cin 
>>  m;
    
while  (m  !=   0 ) {
        cin 
>>  pre  >>  post;
        
if  (pre.length()  !=  post.length())
            cout 
<<   0   <<  endl;
        
else
            cout 
<<  process(m, pre, post)  <<  endl;
        cin 
>>  m;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值