前序、前中、中后序生成二叉树
作者:互联网
中序后序生成树
bitree In_rear_creatTree(char rear[],int rstart,int rend,char in[],int istart,int iend){
//后中双遍历创造树
if(rstart > rend)
return NULL;
bitree t = new bitTree();
char ch = rear[rend]; //获得根结点 后序遍历的根结点在尾部
t->val = ch; //赋值
int i = 0;
while(in[i] != ch)i++;
//根据根结点在中序遍历中找到分界点
t->left = In_rear_creatTree(rear,rstart,rstart+i-istart-1,in,istart,i-1);
t->right = In_rear_creatTree(rear,rstart+i-istart,rend-1,in,i+1,iend);
return t;
}
bitree preInitTree(){ //前序生成此树
bitree t;
char ch;
ch = getchar();
if(ch == '@') return NULL; //符号@代表改结点为null
t = new bitTree();
t->val = ch;
t->left = preInitTree();
t->right = preInitTree();
return t;
}
bitree pre_In_creatTree(char pre[],int pstart,int pend,char in[],int istart,int iend){
//前中双遍历创造树
if(pstart > pend)
return NULL;
bitree t = new bitTree();
char ch = pre[pstart]; //获得根结点 前序遍历的根结点在头部
t->val = ch; //赋值
int i = 0;
while(in[i] != ch)i++;
//根据根结点在中序遍历中找到分界点
t->left = pre_In_creatTree(pre,pstart+1,pstart+i-istart,in,istart,i-1);
t->right = pre_In_creatTree(pre,pstart+i-istart+1,pend,in,i+1,iend);
return t;
}
标签:pre,ch,istart,前中,前序,char,int,二叉树,rear 来源: https://blog.csdn.net/weixin_46258925/article/details/110588340