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

#include
#include
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);
}

你可能感兴趣的:(二叉树)