已知一棵二叉树的先序序列和中序序列,建立该二叉树的二叉链表

#include<stdio.h>
#include<stdlib.h>
typedef int status;
typedef struct BiTNode
{
	int data;
	struct BiTNode* lchild, *rchild;
}BiTNode, *BiTree;
/*
BiTree creat()
{
    BiTree root = (BiTree)malloc(sizeof(BiTNode));
    int x;
    scanf("%d", &x);
    if(x==-1)
        root = NULL;
    else
    {
        root->data = x;
        root->lchild = creat();
        root->rchild = creat();
    }
    return root;
}
*/
//利用先序遍历和中序遍历建一棵树

BiTree creat2(int a[],int b[],int l1,int r1,int l2,int r2)
{
    if(l1<=r1)
    {
        int i=0,llen=0,rlen=0;
        for(i=0;b[i]!=a[l1];i++);//退出循环时i为a[l1]在中序序列的下标
        
        llen=i-l2, rlen=r2-i;
        BiTree t=(BiTree)malloc(sizeof(BiTNode));
        t->data = a[l1];
        t->lchild=creat2(a,b,l1+1,l1+llen,l2,l2+llen-1);
        t->rchild=creat2(a,b,l1+llen+1,r1,l2+llen+1,r2);
    }
    else return NULL;
}

void print(BiTree bt)
{
    if(bt)
    {
        printf("%d ", bt->data);
        print(bt->lchild);
        print(bt->rchild);
    }
}
int main()
{
    int a[100], b[100];
    int n, x, i;
    printf("长度:\n");
    scanf("%d", &n);
    
    printf("先序序列:\n");
    for(i=0;i<n;i++)
    {
        scanf("%d", &x);
        a[i]=x;
    }
    
    printf("后序序列:\n");
    for(i=0;i<n;i++)
    {
        scanf("%d", &x);
        b[i]=x;
    }
    
    BiTree bt=creat2(a,b,0,n-1,0,n-1);
    print(bt);
}
  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值