建立二叉树的二叉链表(严6.65)根据先序序列和中序序列输出后序序列

 

Description

已知一棵二叉树的前序序列和中序序列分别存于两个一维数组中,试编写算法建立该二叉树的二叉链表

 

 

Input

分两行分别输入一棵二叉树的前序序列和中序序列。

 

 

Output

输出该二叉树的后序序列。

 

 

SampleInput        ABDFGCEH

                               BFDGACEH

 

 

 

SampleOutput      FGDBHECA

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct node
{
    char data;
    struct node*lchild;
    struct node*rchild;
}BiTNode,*BiTree;
void midprecreat(BiTree*root,char mid[],char pre[],int lm,int rm,int lp,int rp)
{
    *root=(BiTree)malloc(sizeof(BiTNode));
    (*root)->data=pre[lp];
    (*root)->lchild=NULL;
    (*root)->rchild=NULL;
   int pos=lm;
   while(mid[pos]!=pre[lp])
        pos++;
    int childlen=pos-lm;//用来控制子树在字符串中的范围
    if(pos>lm)//有左子树,递归创建
        midprecreat((&((*root)->lchild)),mid,pre,lm,pos-1,lp+1,lp+childlen);
    if(pos<rm)//有右子树,递创建
        midprecreat((&((*root)->rchild)),mid,pre,pos+1,rm,lp+childlen+1,rp);
}
void print(BiTree p)
{      if(p != NULL)
       {
              print(p->lchild);  //遍历左子树
              print(p->rchild); //遍历右子树
              printf("%c",p->data);     //输出该结点
       }
}
int main()
{
    char    pre[100];            //存储先序序列
    char    mid[100];            //存储中序序列
    int n;
    BiTree root;
    gets(pre);
    n=strlen(pre);
    gets(mid);
    midprecreat(&root,mid,pre,0,n-1,0,n-1);
    print(root);
    return 0;
}

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值