分别由先序与中序以及中序和后序来恢复二叉树

  1. 通过先序和中序:
void PreInOd(char preod[],int i,int j,char inod[],int k,int h,BiTree *t)
{
    int m;
    *t=(BiTNode*)malloc(sizeof(BiTNode));
    (*t)->data=preod[i];
    m=k;
    while(inod[m]!=preod[i])
        m++;
    if(m==k) (*t)->lchild=NULL;
    else InPostOd(preod,i+1,i+m-k,inod,k,m-1,&((*t)->lchild));

    if(m==h) (*t)->rchild=NULL;
    else InPostOd(preod,j-h+m+1,j,inod,m+1,h,&((*t)->rchild));
}

2.通过后序和中序

void InPostOd(char postod[],int i,int j,char inod[],int k,int h,BiTree *t)
{
    int m;
    *t=(BiTNode*)malloc(sizeof(BiTNode));
    (*t)->data=postod[j];
    m=k;
    while(inod[m]!=postod[j])
        m++;
    if(m==k) (*t)->lchild=NULL;
    else InPostOd(postod,i,i+m-1-k,inod,k,m-1,&((*t)->lchild));

    if(m==h) (*t)->rchild=NULL;
    else InPostOd(postod,j-h+m,j-1,inod,m+1,h,&((*t)->rchild));
}

3.顺便总结一下我们老师出的一道题:通过后续和中序来打印一个二叉树,要求恢复成满二叉树后打印。

void LevelOrder(BiTree bt,int h)        //h为深度
{
    BiTNode *queue[MAXNODE],*p;
    int front=-1,rear=0,i,k=pow(2,h)-1;
    queue[rear]=bt;
    while(k--){
        front++;
        printf("%c",queue[front]->data);
        if(queue[front]->lchild!=NULL&&queue[front]!=NULL){
            rear++;
            queue[rear]=queue[front]->lchild;
        }
        else{
            p=(BiTNode*)malloc(sizeof(BiTNode));
            p->data='0';
            p->lchild=NULL;
            p->rchild=NULL;
            rear++;
            queue[rear]=p;
        }
        if(queue[front]->rchild!=NULL&&queue[front]!=NULL){
            rear++;
            queue[rear]=queue[front]->rchild;
        }
        else{
            p=(BiTNode*)malloc(sizeof(BiTNode));
            p->data='0';
            p->lchild=NULL;
            p->rchild=NULL;
            rear++;
            queue[rear]=p;
        }
    }
}

来总结一下:
1)当为空的时候,就新建一个,将其中的数值域赋值为字符0.(如果不新建,下次从他开始找的时候,它是不存在的),洗澡的时候突然有的想法,也是很奇葩。。。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值