题意:
给出一棵K叉树的前序和后序遍历,问中序遍历有多少种
解法:
之所以中序遍历会有多种,原因是存在不满儿子的节点,导致树的形态有不同
通过前序和后序遍历,可以将每一棵子树划分出来,然后递归的累乘计算个数(乘法原理),最后再乘以C
kn,n为当前节点的子树个数
代码:
1
# include <cstdio>
2
using namespace std;
3
# include <cstdlib>
4
# include <cstring>
5
char pre[50],post[50];
6
int c[21][21],k;
7
int solve(int s1,int s2,int l)
8

{
9
int ans=1,co=0,last;
10
for(int i=s1+1;i<s1+l;i+=s2-last)
11
{
12
last=s2;
13
co++;
14
for(;post[s2]!=pre[i];s2++);
15
ans*=solve(i,last,++s2-last);
16
}
17
return ans*c[k][co];
18
}
19
int main()
20

{
21
memset(c,0,sizeof(c));
22
for(int i=0;i<=20;i++) c[i][0]=c[i][i]=1;
23
for(int i=1;i<=20;i++)
24
for(int j=1;j<i;j++)
25
c[i][j]=c[i-1][j-1]+c[i-1][j];
26
while(scanf("%d%s%s",&k,pre,post)==3)
27
printf("%d\n",solve(0,0,strlen(pre)));
28
return 0;
29
}
30