这个代码网上不要太多了,考研复习,贴出比较容易理解的代码,但是写得丑(只是写了比较完整的思路,你看我类型定义都没定义呢)。。。
前序、中序确定二叉树
void preInCreat(Tree r,ElemType a[],ElemType b[],int as,int ad,int bs,int bd)
{
//as:A数组第一个元素的下标,as:A数组最后一个元素下标,bs,as,bs初值为1
if(as>ad)
return;
r=(treeNode*)malloc(sizeof(treeNode));
r->data=a[as];
int i;
for(i=bs;b[i]!=r->data;i++)
int llenth=i-bs;//左子树长度
int rlenth=bd-i;//右子树长度
if(llenth)
preInCreat(r->lchild,a,b,as+1,as+llenth,bs,bs+llen-1);
else
r->lchild=NULL;
if(rlenth)
preInCreat(r->rchild,a,b,ad-rlen+1,ad,bd-rlenth+1,bd);//关于下标问题一定要画画图搞搞清楚
else
r->rchild=NULL;
}
后序、中序确定二叉树
void postInCreat(Tree r,ElemType a[],ElemType b[],int as,int ad,int bs,int bd)
{
if(as>ad)
return;
r=(treeNode*)malloc(sizeof(treeNode));
r->data=a[ad];//后序遍历根结点是最后一个元素
int i;
for(i=bs;b[i]!=r->data;i++)
int llenth=i-bs;
int rlenth=bd-i;
if(llenth)
postInOrder(r->lchild,a,b,as,as+llenth-1,bs,bs+llenth-1);
else
r->lchild=NULL;
if(rlenth)
postInOrder(r->rchild,a,b,ad-rlenth,ad-1,bd-r+1,bd);
else
r->rchild=NULL;
}
本文提供了使用前序、中序及后序、中序遍历序列构造二叉树的算法实现。通过递归方式,根据不同的遍历序列确定二叉树的结构。适用于计算机科学学习者,特别是正在准备研究生入学考试的学生。
1429

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



