中南大学在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; //返回构建出的二叉树的根节点地址
}