前序中序/后序中序确定二叉树

来源:互联网 发布:并行计算的编程模型 编辑:程序博客网 时间:2024/06/06 05:00

这个代码网上不要太多了,考研复习,贴出比较容易理解的代码,但是写得丑(只是写了比较完整的思路,你看我类型定义都没定义呢)。。。
前序、中序确定二叉树

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;}
原创粉丝点击