第4章第1节练习题13 根据先序序列和中序序列建立二叉树

来源:互联网 发布:知乎2016年度100问 编辑:程序博客网 时间:2024/06/06 08:36

问题描述

假设一颗二叉树中各节点的值互不相同,其先序遍历序列和中序遍历序列分别存于两个一维数组A[]B[] 中,试编写算法建立该二叉树的二叉链表

算法思想

由先序和中序序列可以唯一确定一颗二叉树,算法的实现步骤如下:

  1. 根据先序序列确定树的根节点;
  2. 根据根节点在中序序列中划分出二叉树的左,右子树包含哪些节点;
  3. 根绝左右子树在先序序列中的相对次序确定子树的根节点,回到步骤1

其基本过程如下图所示:

二叉树过程

算法描述

BiTNode* InJudge(ElemType* A,ElemType* B,int l1,int h1,int l2,int h2){    int i;    int llen;    int rlen;    BiTNode* T;    T=(BiTNode*)malloc(sizeof(BiTNode));    T->data=A[l1];    for(i=l2;B[i]!=T->data;i++);    llen=i-l2;    rlen=h2-i;    if(llen!=0){        T->lchild=InJudge(A,B,l1+1,l1+llen,l2,l2+llen-1);    }else{        T->lchild=NULL;    }    if(rlen!=0){        T->rchild=InJudge(A,B,h1-rlen+1,h1,h2-rlen+1,h2);    }else{        T->rchild=NULL;    }    return T;}

具体代码见附件。


附件

#include<stdio.h>#include<stdlib.h>#define MaxSize 10typedef char ElemType;typedef struct BiTNode{    ElemType data;    struct BiTNode *lchild, *rchild;}BiTNode,*BiTree;typedef struct{    BiTNode* data[MaxSize];    int front,rear;}SqQueue;//---------------------------------------------------------------void InitQueue(SqQueue*);void EnQueue(SqQueue*,BiTNode*);BiTNode* DeQueue(SqQueue*);int IsEmptyQueue(SqQueue*);BiTNode* CreateBiTree(BiTNode*);BiTNode* InJudge(ElemType*,ElemType*,int,int,int,int);void LevelOrder(BiTNode*);//---------------------------------------------------------------int main(int argc,char* argv[]){    BiTNode* T;    ElemType A[MaxSize]={'A','B','C','D','E','F','G','H','I'};    ElemType B[MaxSize]={'B','C','A','E','D','G','H','F','I'};    T=InJudge(A,B,0,8,0,8);    LevelOrder(T);    printf("\n");    return 0;}//---------------------------------------------------------------BiTNode* InJudge(ElemType* A,ElemType* B,int l1,int h1,int l2,int h2){    int i;    int llen;    int rlen;    BiTNode* T;    T=(BiTNode*)malloc(sizeof(BiTNode));    T->data=A[l1];    for(i=l2;B[i]!=T->data;i++);    llen=i-l2;    rlen=h2-i;    if(llen!=0){        T->lchild=InJudge(A,B,l1+1,l1+llen,l2,l2+llen-1);    }else{        T->lchild=NULL;    }    if(rlen!=0){        T->rchild=InJudge(A,B,h1-rlen+1,h1,h2-rlen+1,h2);    }else{        T->rchild=NULL;    }    return T;}void LevelOrder(BiTNode* T){    BiTNode *p=T;    SqQueue Q;    InitQueue(&Q);    EnQueue(&Q,p);    while(IsEmptyQueue(&Q)!=0){        p=DeQueue(&Q);        printf("%c",p->data);        if(p->lchild!=NULL){            EnQueue(&Q,p->lchild);        }        if(p->rchild!=NULL){            EnQueue(&Q,p->rchild);        }    }}//---------------------------------------------------------------void InitQueue(SqQueue* Q){    Q->front=0;    Q->rear=0;}void EnQueue(SqQueue* Q,BiTNode* T){    if((Q->rear+1)%MaxSize==Q->front){        return;    }    Q->data[Q->rear++]=T;}BiTNode* DeQueue(SqQueue* Q){    if(Q->front==Q->rear){        return NULL;    }    return Q->data[Q->front++];}int IsEmptyQueue(SqQueue* Q){    if(Q->front==Q->rear){        return 0;    }    return -1;}
0 0
原创粉丝点击