前序+后序遍历种类

原文链接:
https://blog.csdn.net/csyifanZhang/article/details/105751387
我的代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define ll long long

ll m;
string prestr,poststr;
ll ans = 1;

ll C(ll a,ll b)
{
    if(b==0) return 1;
    ll tmp1 = 1; ll tmp2 = 1;
    for(int i=1;i<=b;i++){
        tmp1 = tmp1*(a-i+1);
        tmp2 = tmp2*i;
    }
    return tmp1/tmp2;
}

ll dfs(string pre,string post){
    int len = pre.length();
    string str1,str2;
    int numtree=0;
    pre = pre.erase(0,1);post = post.erase(len-1,1);  //去掉首部,去掉末尾
    len--;
    if(len==0){
        return 0;
    }
    if(pre[0] == post[len-1]){  //只有一颗子树
        ll n=0;n=dfs(pre,post);
        ans = ans*C(m,n);//cout<<n<<endl;
        return 1;
    }else{  //多棵子树
        while(pre.length()!=0){
            for(int i=0;i<pre.length();i++){  //搜寻一棵子树
                if(post[i]==pre[0]){
                    str1 = pre.substr(0,i+1);pre.erase(0,i+1);
                    str2 = post.substr(0,i+1);post.erase(0,i+1);
                    ll n=0;n=dfs(str1,str2);//cout<<n<<endl;
                    ans = ans*C(m,n);//cout<<ans<<endl;
                    numtree++;break;
                }
            }
        }
        return numtree;
    }
}

int main()
{
    while(cin>>m){
        ans = 1;
        cin>>prestr>>poststr;
        ll n=dfs(prestr,poststr);
        ans = ans*C(m,n);
        cout<<ans<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值