codevs (wikioi)1029遍历问题

来源:互联网 发布:基于java的web服务器 编辑:程序博客网 时间:2024/05/19 19:33
题目大意:

已知一个二叉树的前序遍历和后序遍历,求出它的中序遍历的种数。


思路:

因为前序遍历的顺序为:根节点->左儿子->右儿子,中序遍历的顺序为:左儿子->根节点->右儿子,后序遍历的顺序为:左儿子->右儿子->根节点,所以当一个节点只有一个儿子时,他在前序遍历和后序遍历中的位置是相同的。因为遍历的都是他的儿子。但是为左儿子还是右儿子会影响他的中序遍历的位置。

所以只需求出只有一个子数的节点的数量n。中序遍历的种数为n^2 。


代码:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
char a[100],b[100];

void init()
{
freopen("live.in","r",stdin);
freopen("live.out","w",stdout);
}


void read()
{
scanf("%s%s",a,b);
}


void work()
{
int la=strlen(a);
int lb=strlen(b);
int cnt=0;
for(int i=1;i<la;i++)
{
for(int j=lb-2;j>=0;j--)
{
if(a[i]==b[j]&&a[i-1]==b[j+1])
{
cnt++;
}
}
}
long long ans=(1<<cnt);
cout<<ans<<endl;
}


int main()
{
init();
read();
work();
return 0;
}

0 0