已知前序、中序,递归建立二叉树(C语言)

#include <stdio.h>
#include <malloc.h>
int pre[]={1,2,4,5,3,6,7};//前序序列
int ino[]={4,2,5,1,6,3,7};//中序序列
struct BTree
{
    struct BTree *left,*right;
    int data;
};//树节点定义
void BuildBTree(struct BTree **T,int preL,int preR,int inoL,int inoR)//递归建树
{
    if(preL>preR) return;
    int e=pre[preL];
    int root=inoL;
    while(ino[root]!=e&&root<=inoR) ++root;
    (*T)=(struct BTree *)malloc(sizeof(struct BTree));
    (*T)->left=NULL;
    (*T)->right=NULL;
    (*T)->data=e;
    BuildBTree(&(*T)->left,preL+1,preL+root-inoL,inoL,root-1);
    BuildBTree(&(*T)->right,preL+root-inoL+1,preR,root+1,inoR);
}
void Treverse(struct BTree *T)//中序遍历
{
    if(T)
    {
        Treverse(T->left);
        printf("%d ",T->data);
        Treverse(T->right);
    }
}
int main()
{
    struct BTree *T=NULL;
    BuildBTree(&T,0,6,0,6);
    Treverse(T);
    return 0;
}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值