7 后序+中序序列构造二叉树

后序+中序序列构造二叉树

输入样例:

第一行输入序列长度n,第二行输入n个字符表示二叉树后序遍历的序列,第三行输入n个字符表示二叉树中序遍历的序列

9
GHDBEIFCA
GDHBAECIF

结尾无空行

输出样例:

输出二叉树先序遍历的序列。

ABDGHCEFI

结尾无空行

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct node{
    char data;
    struct node *lchild;
    struct node *rchild;    
}bitnode,*bitree;

void creattree(bitree &T,char *hou,char *zhong,int len){//后序中序建立二叉树
    if(len<=0){T=NULL;return;}
    T=(bitree)malloc(sizeof(bitnode));
    T->data=hou[len-1];
    char *p1,*p2,p[2];
    p[0]=hou[len-1];
    p[1]='\0';
    p1=strtok(zhong,p);
    p2=strtok(NULL,p);
    int ln;
    if(p1!=NULL) ln=strlen(p1);
    else ln=0;
    char *q1,*q2;
    q1=(char*)malloc(sizeof(char)*(ln+1));
    q2=(char*)malloc(sizeof(char)*(len-ln));
    int i;
    for(i=0;i<ln;i++)
        q1[i]=hou[i];
    q1[i]='\0';
    for(i=ln;i<len-1;i++)
        q2[i-ln]=hou[i];
    q2[i-ln]='\0';
    if(p1==NULL){
        T->lchild=NULL;
        //creattree(T->rchild,p2,q2,len-ln-1);
    }
    if(p2==NULL){
        T->rchild=NULL;
        //creattree(T->lchild,p1,q1,ln);
    }
    
    if(p1!=NULL) {
        creattree(T->lchild,q1,p1,ln);
        //creattree(T->rchild,p2,q2,len-ln-1);
    }
    if(p2!=NULL){
        creattree(T->rchild,q2,p2,len-ln-1);
    }

}

void pre(bitree T){
        if(T==NULL)return;
        printf("%c",T->data);
        if(T->lchild)pre(T->lchild);
        if(T->rchild)pre(T->rchild);

        

}

int main(){
    char *hou,*zhong;
    int n;
    scanf("%d",&n);
    getchar();
    hou=(char*)malloc(sizeof(char)*(n+1));
    zhong=(char*)malloc(sizeof(char)*(n+1));
    scanf("%s",hou);    
    scanf("%s",zhong);
    //printf("%s\n%s\n",hou,zhong);
    bitree T;
    creattree(T,hou,zhong,n);
    pre(T);

    system("pause");
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值