树的遍历转换(前序中序转后序,后序中序转前序)C++

注:只知道前序后序不一定能确定唯一的二叉树,因为只能确定父子节点而无法确定左右子树。

前序中序转后序
算法描述

1在前序序列中找到根节点
2在中序序列中查找这个根节点,确定左右子树。
3对左右子树递归进行步骤1,2。
4输出根节点

递归实现
#include<iostream>
#include<string>
using namespace std;
string pre, in;
void creatTree(int s, int e, int rootindex) {//s,e,中序的子树范围,前序中的根节点下标
    if (s <=e) {//递归出口s>e
        int index = s;
        while (in[index] != pre[rootindex]) { index++; }//在中序中查找根节点。
        creatTree(s, index - 1, rootindex + 1);//左子树
        creatTree(index + 1, e, rootindex + 1 + (index - s));//右子树
        cout << in[index];//根节点
    }
}
int main() {
    cin >> pre >> in;
    creatTree(0, in.size() - 1, 0);
    return 0;
}
/*数据前序中序
ACDEFHGB
DECAHFBG
结果
EDCHBGFA*/
后序中序转前序
算法描述

1在后序序列中找到根节点
2在中序序列中找到该根节点的位置,确定左右子树范围
3输出根节点
3对左右子树递归重复步骤1,2,3。

递归代码
#include<iostream>
#include<string>
using namespace std;
string post, in;
void creatTree(int s, int e, int rootindex) {//s,e,中序的子树范围,后序中的根节点下标
    if (s <=e) {//递归出口s>e
        int index = s;
        while (in[index] != post[rootindex]) { index++; }//在中序中查找根节点。
        cout << in[index];//根节点
        creatTree(s, index - 1, rootindex -1-(e-index));//左子树
        creatTree(index + 1, e, rootindex -1);//右子树
    }
}
int main() {
    cin >> in >> post;
    creatTree(0, in.size() - 1, post.size() - 1);
    return 0;
}
/*数据中序后序
ADEFGHMZ
AEFDHZMG
输出
GDAFEMHZ
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值