通过前序,中序求后序 或 通过后序,中序求前序

//通过前序,中序求后序 或 通过后序,中序求前序
//测试数据 前序DBACEGF 中序ABCDEFG 后序ACBFGED
#include<bits/stdc++.h>
using namespace std;
struct node{
    char data;
    node *lchild,*rchild;
};
string prestr,instr,poststr;//前序,中序,后序

node *creatPreIn(int preL,int preR,int inL,int inR){
    //通过前序,中序建立节点
    //preL前序左端点,preL前序右端点,inL中序左端点,inR中序右端点
    if(preL>preR)return NULL;
    node *root=new node;
    root->data=prestr[preL];
    int k;
    for(k=inL;k<=inR;k++)//在中序中找到preL的字符
        if(instr[k]==prestr[preL])break;
    int numLeft=k-inL;
    root->lchild=creatPreIn(preL+1,preL+numLeft,inL,k-1);
    root->rchild=creatPreIn(preL+numLeft+1,preR,k+1,inR);
    return root;
}
node *creatPostIn(int postL,int postR,int inL,int inR){
    //通过后序,中序建立节点
    //postL后序左端点,postR后序右端点,inL中序左端点,inR中序右端点
    if(postL>postR)return NULL;
    node *root=new node;
    root->data=poststr[postR];
    int k;
    for(k=inL;k<=inR;k++)//在中序中找到postR的字符
        if(instr[k]==poststr[postR])break;
    int numLeft=k-inL;
    root->lchild=creatPostIn(postL,postL+numLeft-1,inL,k-1);
    root->rchild=creatPostIn(postL+numLeft,postR-1,k+1,inR);
}
void postOrder(node *root){
    //后序遍历
    if(root==NULL)return;
    postOrder(root->lchild);
    postOrder(root->rchild);
    printf("%c",root->data);
}
void preOrder(node *root){
    //前序遍历
    if(root==NULL)return;
    printf("%c",root->data);
    preOrder(root->lchild);
    preOrder(root->rchild);
}
int main(){
    int model;
    printf("通过前序,中序求后序输入1,通过后序,中序求前序输入2\n");
    cin>>model;
    if(model==1){
        while(cin>>prestr>>instr){
        //通过前序,中序求后序
            node *root;
            root=creatPreIn(0,prestr.length()-1,0,instr.length()-1);
            postOrder(root);
            printf("\n");
        }
    }
    if(model==2){
        while(cin>>poststr>>instr){
        //通过后序,中序求前序
            node *root;
            root=creatPostIn(0,poststr.length()-1,0,instr.length()-1);
            preOrder(root);
            printf("\n");
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值