已知中序和先序|后序,建立二叉树及三种方式遍历

const int maxv= 10000+10;
int n;
int in_order[maxv],post_order[maxv],pre_order[maxv];
int lch[maxv],rch[maxv]; //左右子节点

int build1(int L1,int R1,int L2,int R2)  //通过中序,后序数组建立二叉树
{
    if(L1>R1) return 0;
    int root = post_order[R2];
    int p = L1;
    while(in_order[p]!=root) p++;
    int cnt = p-L1;
    lch[root] = build1(L1,p-1,L2,L2+cnt-1);
    rch[root] = build1(p+1,R1,L2+cnt,R2-1);
    return root;
}

int build2(int L1, int R1, int L2, int R2) //通过先序,中序数组建立二叉树,返回树根
{
    if(L1>R1) return 0;
    int root = pre_order[L1];
    int p = L2;
    while(in_order[p]!=root) p++;
    int cnt = p-L2;
    lch[root] = build2(L1+1,L1+cnt,L2,p-1);
    rch[root] = build2(L1+cnt+1,R1,p+1,R2);
    return root;
}



void post_reverse(int root)  //后序遍历
{
    if(root)
    {
        post_reverse(lch[root]);
        post_reverse(rch[root]);
        printf("%d ",root);
    }
}

void in_reverse(int root)  //中序遍历
{
    if(root)
    {
        post_reverse(lch[root]);
        printf("%d ",root);
        post_reverse(rch[root]);
    }
}

void pre_reverse(int root)  //先序遍历
{
    if(root)
    {
        printf("%d ",root);
        post_reverse(lch[root]);
        post_reverse(rch[root]);
    }
}

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值