设一棵二叉树各结点的值互不相同,其先序遍历序列和中序遍历序列分别存于两个一维数组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;
}

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
以下是使用Python实现给定一棵二叉树先序遍历序列中序遍历序列的代码: ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def buildTree(preorder, inorder): if not preorder or not inorder: return None root_val = preorder[0] root = TreeNode(root_val) root_index = inorder.index(root_val) root.left = buildTree(preorder[1: 1+root_index], inorder[:root_index]) root.right = buildTree(preorder[1+root_index:], inorder[root_index+1:]) return root ``` 这个函数的输入参数包括先序遍历序列中序遍历序列,返回是构建出的二叉树的根节点。在函数内部,首先检查先序遍历序列中序遍历序列是否为空。如果有任何一个为空,则返回None。否则,我们可以确定根节点的先序遍历序列的第一个元素root_val。接下来,我们在中序遍历序列找到root_val的索引位置root_index,为了构建二叉树,我们将中序遍历序列分成两半:inorder[:root_index]是左子树的中序遍历序列,inorder[root_index+1:]是右子树的中序遍历序列。对应地,通过切片操作,我们将先序遍历序列分为两个部分:preorder[1:1+root_index]是左子树的先序遍历序列,preorder[1+root_index:]是右子树的先序遍历序列。最后,我们递归地构建左子树和右子树,并将其分别赋给根节点的left和right属性。整个过程结束后,我们返回根节点root。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值