设一棵二叉树各结点的值互不相同,其先序遍历序列和中序遍历序列分别存于两个一维数组A[1...n]和B[1...n]中,试编写算法建立该二叉树的二叉链表

难想啊…

#include <stdio.h>
#include <malloc.h>


typedef int elemtype;
typedef struct BTNode {
    elemtype data;
    struct BTNode *left, *right;
}BTNode, *BiTree;

BiTree creat(elemtype A[], elemtype B[], int l1, int r1, int l2, int r2)
{
    BiTree root = (BiTree)malloc(sizeof(BTNode));
    root->data = A[l1];
   // printf("%d\n",root->data);
    int i = l2;
    for(i=l2; B[i] != A[l1]; i++);  //在中序遍历序列中查找根结点位置
    int llen = i - l2;  //左子树长度
    int rlen = r2-i;    //右子树长度
    if(llen>0)
        root->left = creat(A, B, l1+1, l1+llen, l2, llen+l2-1);
    else
        root->left = NULL;
    if(rlen>0)
        root->right = creat(A, B, r1-rlen+1, r1, r2-rlen+1, r2);
    else
        root->right = NULL;

    return root;
}

void print(BiTree bt)
{
    if (bt!=NULL)
    {
        printf ("%d", bt->data);
        print(bt->left);
        print(bt->right);
    }
}

int main()
{
    int n;
    elemtype x;
    printf("请输入二叉树的结点个数:\n");
    scanf("%d", &n);
    elemtype A[n+1], B[n+1];
    printf("请输入二叉树的先序遍历序列:\n");
    for(int i=1; i<=n; i++)
    {
        scanf("%d", &x);
        A[i] = x;
    }
    printf("请输入二叉树的中序遍历序列:\n");
    for(int j=1; j<=n; j++)
    {
        scanf("%d", &x);
        B[j] = x;
    }
    
    BiTree bt = creat(A, B, 1, n, 1, n);
    
    print(bt);
    
    return 0;
}

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