//通过前序,中序求后序 或 通过后序,中序求前序
//测试数据 前序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;
}
通过前序,中序求后序 或 通过后序,中序求前序
最新推荐文章于 2021-01-06 22:40:42 发布