二叉树遍历问题

给定二叉树的先序遍历和后序遍历,计算可能有几棵二叉树

Input

本问题有多组测试数据,第一行是测试数据的组数n,紧接着是n组测试数据。每组测试数据有两行,分别表示二叉树的先序遍历和后序遍历,每个结点用大写字母表示,输入保证数据是正确的。

Output

对于每一组输入,对应的输出只有一行,即符合给定的先序遍历和后序遍历这样条件的二叉树的棵数。

Sample Input
1
ABDCEFG
DBEGFCA

Sample Output
4

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1000+7,INF=0x3f3f3f3f;
char pre[N],aft[N];
ll quick(ll x,ll y)
{
    ll ans=1;
    while(y)
    {
        if(y&1) ans*=x;
        x*=x;
        y>>=1;
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s%s",pre,aft);
        int len=strlen(pre);
        ll cnt=0;
        for(int i=0;i<len-1;i++)   
            for(int j=1;j<len;j++)
                if(pre[i]==aft[j]&&pre[i+1]==aft[j-1]) cnt++;
        printf("%lld\n",quick(2,cnt));
    }
}

猜你喜欢

转载自blog.csdn.net/oinei/article/details/81032932