2月4日总结

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;
}

当前序遍历和后序遍历确定,只有当一个结点只有一个子树时,中序遍历序列的的总数翻倍。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值