树的建立
已知先序中序求后续
#include<bits/stdc++.h>
using namespace std;
typedef struct BiTNode
{
char data;
BiTNode *lchild;
BiTNode *rchild;
}BiTNode,*tree;
BiTNode* creat(char *pre, char *in, int n)
{
int i = 0;
int n1 = 0,n2 = 0;
int m1 = 0,m2 = 0;
BiTNode*node = NULL;
char lpre[1001],rpre[1001];
char lin[1001],rin[1001];
if(n==0)
return NULL;
node=(BiTNode*)malloc(sizeof(BiTNode));
memset(node,0,sizeof(BiTNode));
node->data=pre[0];
for(i=0;i<n;i++){
if (i<=n1&&in[i]!=pre[0]){
lin[n1++] = in[i];
}
else if(in[i]!=pre[0]){
rin[n2++] = in[i];
}
}
for(i=1;i<n;i++){
if (i<(n1+1)){
lpre[m1++]=pre[i];
}
else{
rpre[m2++]=pre[i];
}
}
node->lchild=creat(lpre,lin,n1);
node->rchild=creat(rpre,rin,n2);
return node;
}
void print(BiTNode *T)
{
if(T)
{
print(T->lchild);
print(T->rchild);
cout<<T->data;
}
}
//层序
void prin(Tree tree)
{
if(tree==NULL)
return;
int i=0,t=0;
struct BitNode *s[10086],*q;
s[0]=tree;
int flag=0;
while(t<=i)
{
q=s[t++];
if(flag)
printf(" %d",q->data);
else
{
printf("%d",q->data);
flag=1;
}
if(q->lchild!=NULL)
s[++i]=q->lchild;
if(q->rchild!=NULL)
s[++i]=q->rchild;
}
}
int main()
{
char a[50],b[50];
int n,i,j,k;
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
getchar();
for(i=0;i<n;i++)
cin>>b[i];
BiTNode* tree=creat(a,b,n);
print(tree);
}