遍历问题
题目描述
我们都很熟悉二叉树的前序、中序、后序遍历,在数据结构中常提出这样的问题:已知一棵二叉树的前序和中序遍历,求它的后序遍历,相应的,已知一棵二叉树的后序遍历和中序遍历序列你也能求出它的前序遍历。然而给定一棵二叉树的前序和后序遍历,你却不能确定其中序遍历序列,考虑如下图中的几棵二叉树:
所有这些二叉树都有着相同的前序遍历和后序遍历,但中序遍历却不相同。
输入格式
输A数据共两行,第一行表示该二叉树的前序遍历结果s1,第二行表示该二叉树的后序遍历结果s2。
输出格式
输出可能的中序遍历序列的总数,结果不超过长整型数。
样例 #1
样例输入 #1
abc
cba
样例输出 #1
4
提示
无提示
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 1e9 + 10;
const int N = 1e6;
//只有一个儿子 的节点 才会在知道 前序后序 的情况下有不同的中序遍历
char a[N];
char b[N];
int ans;
int main(){
cin >> a;
cin >> b;
for(int i = 0;i < strlen(a);i ++)
for(int j = 1;j < strlen(b);j ++){
if(a[i] == b[j]&&a[i + 1] == b [j - 1])
ans++;
}
cout << pow(2,ans)<< endl;
system("pause");
return 0;
}