【递归】中序-后序构造二叉树

中南大学在2019年算法题部分考察了由先序中序构造二叉树算法,本文出于备考角度,将给出依靠递归算法由中序后序序列构造二叉树过程,本算法只涉及核心代码(C++),其余考完补充。

struct node{
        int data;           //数据域
        node *left;         //左孩子
        node *right;        //右孩子
};
int in[max],post[max];

//当前二叉树遍历的后序遍历区间为[postL,postR],中序遍历区间为[inL,inR]
//由create函数返回构建出的二叉树的根节点地址

node *create(int postL,int postR,int inL,int inR){
    if( postL > postR ) return Null;  //区间越界
    node *root = new node();          //创建新节点(根)
    root->data = post[postR];         //新节点数据域为根节点的值
    int cur;    
    for(cur=inL; cur<=inR; cur++){    //遍历确定根节点及左右子树区间
        if(in[cur] == post[postR]) break;
    }
    int numLeft=cur-inL;              //左子树中根节点个数
    root->left = create(postL,postL+numLeft-1,inL,cur-1);//递归左子树
    root->right = create(postL+numLeft,postR,cur+1,inR); //递归右子树
    return root;                      //返回构建出的二叉树的根节点地址
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值