BiTree PreInCreat(ElemType A[],ElemType B[],int l1,int h1,int l2,int h2){
//l1,h1为先序的首尾;l2,h2为中序的首尾;A[]为先序,B[]为中序
root=(BiTNode*)malloc(sizeof(BiTNode));
root->data=A[l1];
for(int i=l2;B[i]!=root->data;i++); //找到根节点在中序序列中的位置
llen=i-l2; //计算出左子树和右子树的长度
rlen=h2-i;
if(llen){ //构建左子树
root->lchild=PreInCreate(A,B,l1+1,l1+llen,l2,l2+llen-1);
}
else{
root->lchild=NULL;
}
if(rlen){ //构建右子树
root->rchild=PreInCreate(A,B,h1-rlen+1,h1,h2-rlen+1,h2);
}
else{
root->rchild=NULL;
}
return root;
}
本文详细解析了如何利用先序遍历和中序遍历序列构造二叉树的递归算法,通过查找根节点在中序序列的位置来确定左右子树的范围,进而递归构建整棵树。
523

被折叠的 条评论
为什么被折叠?



