C++中二叉树的重建,实现根据中序遍历和后序遍历/前序遍历得到前序遍历/后序遍历

根据中序遍历和后序遍历得到前序遍历

1、后序遍历的结果中最后个元素一定是根节点
2、后序遍历结果= 左子树后序结构+根节点+右子树后序结果
3、中序遍历结果= 左子树的中序结果+根节点+右子树的中序结果

#include <iostream>
#include<algorithm>
#include<vector>
using namespace std;
//根据中序遍历和后序遍历得到前序遍历
void recon2(vector<int>&in2,vector<int>&post) {
    if (post.size()==0) return;
    pos = post.size();
    int root = post[pos-1];
    cout << root << " ";
    int m = distance(in2.begin(), find(in2.begin(), in2.end(), root));//判断节点root在中序遍历中的位置
    vector<int>in3(in2.begin(),in2.begin()+m);//将中序遍历中节点root的左子树取出
    vector<int>post3(post.begin(),post.begin()+m);//将后序遍历中节点root的左子树取出
    recon2(in3,post3);//重建左子树

    vector<int>in4(in2.begin() + m + 1, in2.end());//将中序遍历中节点root的右子树取出
    vector<int>post4(post.begin() + m, post.end()-1);//将后序遍历中节点root的右子树取出
    recon2(in4, post4);//重建右子树
}
int main()
{
	int n2;//节点的个数
    cin >> n2;
    int k;
    int* A = new int[n2];
    //由中序遍历和后序遍历得到前序遍历
    vector<int>in2;
    cout << "请输入树的中序遍历序号:" << endl;
    for (int i = 0; i < n2; i++) {
        cin >> k;
        in2.push_back(k);
    }
    vector<int>post;
    cout << "请输入树的后序遍历序号:" << endl;
    for (int i = 0; i < n2; i++) {
        cin >> k;
        post.push_back(k);
    }
    cout << "树的后序遍历为序号为:" << endl;
    recon2(in2, post);

    delete[]A;
    return 0;
}

程序运行结果

由前序遍历和中序遍历得到后序遍历

1、先序遍历的结果中第一个元素一定是根节点
2、先序遍历结果= 根节点+左子树先序结构+右子树先序结果
3、中序遍历结果= 左子树的中序结果+根节点+右子树的中序结果

#include <iostream>
#include<algorithm>
#include<vector>
using namespace std;
//根据前序遍历和中序遍历得到后序遍历
vector<int>in;//中序遍历序列
int pos = 0;//节点序号
void reconstruction(int l, int r, int pre[]) {
    if (l == r) return;
    int c = pre[(pos)++];
    int m = distance(in.begin(), find(in.begin(), in.end(), c));
    reconstruction(l, m, pre);//重建左子树
    reconstruction(m+1, r, pre);//重建右子树
    cout << c << " ";
}
int main()
{
	int n2;
    cin >> n2;
    int k;
    int* A = new int[n2];

    cout << "请输入前序遍历序号:" << endl;
    for (int i = 0; i < n2; i++) {
        cin >> A[i];
        
    }
    cout << "请输入中序遍历序号:" << endl;
    for (int i = 0; i < n2; i++) {
        cin >> k;
        in.push_back(k);
    }
    cout << "后序遍历为:" << endl;
    reconstruction(0, n2, A);
    delete[]A;
    return 0;
}

程序运行结果

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值