根据树的前序中序写出后序或后序中序写出前序遍历

#include<bits/stdc++.h>
//#define int long long
using namespace std;

int back[]={5,2,6,4,1},mid[]={2,5,1,6,4},pre[]={1,2,5,4,6};
//string back,mid;

void getback(int l,int r,int root){//通过前序和中序得到后序
    if(l>r)return;
    int i = l;
    while (i<=r&&mid[i]!=back[root]) i++;
    getback(l,i-1,root+1);
    getback(i+1, r,root+1+i-l);//i-l为相对偏移量,思考的时候可以用整个树的根节点思考,当查找右子树的时候应该加上其左子树的节点个数
    cout<<mid[i];//输出后序遍历结果
}

void gethead(int l,int r,int root){//通过后序和中序得到前序
    if(l>r)return;
    int i = l;
    while (i<=r&&mid[i]!=back[root]) i++;
    cout<<mid[i];
    gethead(l,i-1,root-1-(r-i));//同理前序遍历,应该减去此时右子树的节点个数
    gethead(i+1, r,root-1);
}


void solve(){
//    getback(0,4,0);
    gethead(0,4,4);//从后往前查
}


signed main() {
    //ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int _ = 1;
//    cin >> _;
    while (_--) {
        solve();
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值