#include<bits/stdc++.h>
using namespace std;
typedef struct bitnode{
char e;
struct bitnode *lchild,*rchild;
}bitnode;
int locate(char c,char *s){
for(int i=0;i<strlen(s);i++){
if(c==s[i]){
return i;
}
}
}
void preordertravse(bitnode *t1){
if(t1!=NULL){
cout<<t1->e<<endl;
preordertravse(t1->lchild);
preordertravse(t1->rchild);
}
}
void inordertravse(bitnode *t1){
if(t1!=NULL){
inordertravse(t1->lchild);
cout<<t1->e<<endl;
inordertravse(t1->rchild);
}
}
void postordertravse(bitnode *t1){
if(t1!=NULL){
postordertravse(t1->lchild);
postordertravse(t1->rchild);
cout<<t1->e<<endl;
}
}
bitnode* creatbitree(char *prestring,char *instring,int startp,int endp,int starti,int endi){
bitnode *root=(bitnode*)malloc(sizeof(bitnode));
root->e=prestring[startp];
int position=locate(root->e,instring);
int lenl=position-starti;
int lenr=endi-position;
if(lenl)
root->lchild=creatbitree(prestring,instring,startp+1,startp+lenl,starti,starti+lenl-1);
else
root->lchild=NULL;
if(lenr)
root->rchild=creatbitree(prestring,instring,endp-lenr+1,endp,endi-lenr+1,endi);
else
root->rchild=NULL;
return root;
}
int main(){
int count=0;
char *pres="abecdfghij";
char *ines="ebcdafhigj";
bitnode *tree;
tree=creatbitree(pres,ines,0,9,0,9);
preordertravse(tree);
cout<<endl;
inordertravse(tree);
cout<<endl;
postordertravse(tree);
}
运行结果:
分别是建好树之后再先序中序后序输出:
欢迎参考学习;