数据结构作业之根据中序和后序表达式创建二叉树

数据结构作业,根据中序和后序表达式创建二叉树

#include 
#include 
#include 
typedef struct binode
{
 char data;
 struct binode *lchild,*rchild;
}Binode,*Bitree;
/*根据中序和后续创建二叉树*/ 
void createbitree(Bitree &L,char inorder[],char postorder[],int lowin,int highin,int lowpo,int highpo)
{
  char e;
  e=postorder[highpo];
  L=(Bitree)malloc(sizeof(Binode));
  L->lchild=L->rchild=NULL;
  L->data=e;
  int root=lowin;
  while(inorder[root]!=e)
  {
   root++;
  }
  int len;
  len=root-lowin;
  
  if(root>lowin)
   createbitree(L->lchild,inorder,postorder,lowin,root-1,lowpo,lowpo+len-1);
  if(root<highin)
   createbitree(L->rchild,inorder,postorder,root+1,highin,lowpo+len,highpo-1);
 
} 
/*递归遍历二叉树*/ 
void preorder(Bitree L)
{
 if(L)
 {
  printf("%c ",L->data);
  if(L->lchild)
  preorder(L->lchild);
  if(L->rchild)
  preorder(L->rchild);
 }
}
int main()
{
 char inorder[100];
 char postorder[100];
 int lowin,highin,lowpo,highpo;
 Bitree L;
 printf("input the inorder:\n");
 scanf("%s",inorder);
 printf("input the postorder:\n");
 scanf("%s",postorder);
 createbitree(L,inorder,postorder,0,strlen(inorder),0,strlen(postorder));
 printf("\n");
 preorder(L);
 return 0;
}

你可能感兴趣的:(数据结构作业)