根据二叉树的先序遍历和中序遍历建立二叉树

根据二叉树的先序遍历和中序遍历建立二叉树

rebacktree 根据二叉树的先序遍历和中序遍历建立二叉树。
rebacktree1 根据二叉树的后序序遍历和中序遍历建立二叉树。
#include "stdio.h"
#include "stdlib.h"
typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}    NODE,*NODEP;

void MidOrder(NODEP p);
NODEP rebacktree (NODEP t,char a[],char b[],int al,int ah,int bl,int bh);
NODEP rebacktree1 (NODEP t,char a[],char b[],int al,int ah,int bl,int bh);
main()
{
/*char a[]="ABDEGHCFIJ";  */
char a[]="DGHEBJIFCA";
char b[]="DBGEHACIJF";
NODEP r=NULL;
r= rebacktree1(r,a,b,0,9,0,9);
MidOrder(r);
printf("/n");


}

void MidOrder(NODEP p)
{
if(p)
{
MidOrder(p->lchild);
printf("%c ",p->data);
MidOrder(p->rchild);
}
}

NODEP rebacktree (NODEP t,char a[],char b[],int al,int ah,int bl,int bh)
{
NODEP r;
int j;
if(al<=ah)
{
r=(NODEP)malloc(sizeof(NODE));
r->data=a[al];
r->lchild=NULL;
r->rchild=NULL;
t=r;
for(j=bl;j<=bh;j++)
{
  if(a[al]==b[j]) break;
}
t->lchild=rebacktree(t->lchild,a,b,al+1,al+j-bl,bl,j-1);
t->rchild=rebacktree(t->rchild,a,b,al+j-bl+1,ah,j+1,bh);
return t;
}
return NULL;
}
NODEP rebacktree1 (NODEP t,char a[],char b[],int al,int ah,int bl,int bh)
{
NODEP r;
int j;
if(al<=ah)
{
r=(NODEP)malloc(sizeof(NODE));
r->data=a[ah];
r->lchild=NULL;
r->rchild=NULL;
t=r;
for(j=bl;j<=bh;j++)
{
  if(a[ah]==b[j]) break;
}
t->lchild=rebacktree1(t->lchild,a,b,al,al+j-bl-1,bl,j-1);
t->rchild=rebacktree1(t->rchild,a,b,al+j-bl,ah-1,j+1,bh);
return t;
}
return NULL;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值