#include<iostream>
#include<cstring>
using namespace std;
typedef struct student
{
student *left;
student *right;
int data;
}*BTree,btree;
void pre_printlist(BTree L);
void mid_printlist(BTree L);
void post_printlist(BTree L);
void creat_bt1(BTree &L,char a[],char b[],int L1,int R1,int L2,int R2); //a为先序序列 b为中序序列
void creat_bt2(BTree &L,char mid[],char post[],int L2,int R2,int L3,int R3); //已知后续中序建树
int main()
{
char pre[]={'4','3','1','2','5','6'};
char mid[]={'1','2','3','4','5','6'};
char post[]={'2','1','3','6','5','4'};
/*char post[]={}*/
int L1=0;
int R1=sizeof(pre)-1;
int L2=0;
int R2=sizeof(mid)-1;
int L3=0;
int R3=sizeof(post)-1;
BTree tree1,tree2;
creat_bt1(tree1,pre,mid,L1,R1,L2,R2);
creat_bt2(tree2,mid,post,L2,R2,L3,R3);
cout<<"tree1 :"<<endl;
cout<<"先序: ";
pre_printlist(tree1);
cout<<endl;
cout<<"中序 ";
mid_printlist(tree1);
cout<<endl;
cout<<"后序 :";
post_printlist(tree1);
cout<<endl;
cout<<"tree2:"<<endl;
cout<<endl;
cout<<"先序: ";
pre_printlist(tree2);
cout<<endl;
cout<<"中序 ";
mid_printlist(tree2);
cout<<endl;
cout<<"后序 :";
post_printlist(tree2);
return 0;
}
void creat_bt1(BTree &L,char pre[],char mid[],int L1,int R1,int L2,int R2) //a为先序序列 b为中序序列
{
if(L1>R1)
{
return ;
}
else
{
L=new btree;
L->data=pre[L1];
L->left=L->right=NULL;
int i;
for(i=L2;i<=R2;i++)
{
if(pre[L1]==mid[i])
{
break;
}
}
creat_bt1(L->left,pre,mid,L1+1,L1+i-L2,L2,i-1);
creat_bt1(L->right,pre,mid,L1+i-L2+1,R1,i+1,R2);
}
}
void creat_bt2(BTree &L,char mid[],char post[],int L2,int R2,int L3,int R3) //已知后续中序建树
{
if(L3>R3)
{
return ;
}
else
{
L=new btree;
L->data=post[R3];
L->left=L->right=NULL;
int i;
for(i=L2;i<=R2;i++)
{
if(post[R3]==mid[i])
{
break;
}
}
creat_bt2(L->left,mid,post,L2,i-1,L3,L3+i-L2-1);
creat_bt2(L->right,mid,post,i+1,R2,L3+i-L2,R3-1);
}
}
void pre_printlist(BTree L)
{
if(L!=NULL)
{
cout<<char(L->data)<<" ";
pre_printlist(L->left);
pre_printlist(L->right);
}
}
void mid_printlist(BTree L)
{
if(L!=NULL)
{
mid_printlist(L->left);
cout<<char(L->data)<<" ";
mid_printlist(L->right);
}
}
void post_printlist(BTree L)
{
if(L!=NULL)
{
post_printlist(L->left);
post_printlist(L->right);
cout<<char(L->data)<<" ";
}
}
已知树的先序中序 或者 中序后续建树(递归)
最新推荐文章于 2021-11-26 16:03:24 发布