1.P1827 [USACO3.4] 美国血统 American Heritage
#include<bits/stdc++.h>
using namespace std;
void dfs(string s1, string s2) {
char root = s2[0];// 获取根节点
int l = s1.find(root), r = s1.size() - l - 1; // 计算左子树和右子树的长度
if (l) {
string s1_l = s1.substr(0, l), s2_l = s2.substr(1, l);
dfs(s1_l, s2_l);
}
if (r) {
string s1_r = s1.substr(l + 1, r), s2_r = s2.substr(l + 1, r);
dfs(s1_r, s2_r);
}
cout << root;// 输出当前子树的根节点
}
int main() {
string s1, s2;
cin >> s1 >> s2;
dfs(s1, s2);
return 0;
}
首先,我们知道前序遍历的第一个节点一定是根节点,我们可以根据前序遍历确定根节点的值。
然后,在中序遍历中,根节点将左右子树分开,左侧为左子树,右侧为右子树。我们可以根据前序遍历中确定的根节点值,在中序遍历中找到对应的位置,将中序遍历划分为左子树和右子树的部分。接着,我们递归处理左子树和右子树,直到左子树或右子树为空为止。
2.P1229 遍历问题
#include<bits/stdc++.h>
using namespace std;
int main(){
string s1, s2;
cin >> s1 >> s2;
int num = 1; // 可能的中序遍历序列总数
for(int i = 0; i <= s1.length() - 2; i++){
for(int j = 0; j <= s1.length() - 1; j++){
if(s1[i] == s2[j] && s1[i + 1] == s2[j - 1]){//判断该结点是否只有1个子树
num *= 2;
}
}
}
cout << num << endl;
return 0;
}
当前序遍历和后序遍历确定,只有当一个结点只有一个子树时,中序遍历序列的的总数翻倍。