王道关于树的代码总结(二)

考研数据结构

树🌲的代码汇总(二)

一、已知满二叉树的先序序列,求其后续序列

void pretopost(int pre[],int l1,int h1,int post[],int l2,int h2){
  if(l1>h1) return;
  post[h2]=pre[l1];
  int half=(h1-l1)/2;
  pretopost(pre,l1+1,l1+half,post,l2,l2+half-1);
  pretopost(pre,l1+half+1,h1,post,l2+half,h2-1);
}

二、将一棵二叉树的叶子结点按从左到右的顺序连成一个单链表

BiTree head=NULL,pre;
void preorder(BiTree bt){
  if(!bt) return;
  if(!bt->lchild&&!bt->rchild){
    if(head==NULL){
      head=pre=bt;
    }else{
      pre->rchild=bt;
      pre=bt;
    }
  }
  preorder(bt->lchild);
  preorder(bt->rchild);
  pre->rchild=NULL;
  return head;
}

三、判断两棵二叉树是否相似

int isSimilar(BiTree b1,BiTree b2){
  if(!b1&&!b2) return 1;
  else if(!b1||!b2) return 0;
  else{
     return isSimilar(b1->lchild,b2->lchild)&&isSimilar(b1->rchild,b2->rchild);
  }
}

四、中序线索树中查找指定结点在后序的前驱结点

BiTree inPostPre(BiTree t,BiTree p){
  BiTree q;
  if(p->rtag==0) q=p->rchild;
  else if(p->ltag==0) q=p->lchild;
  else if(!p->lchild) q=NULL;
  else{
    while(p->ltag==1&&p->lchild){
      p=p->lchild;
    }
    if(p->ltag==0){
      q=p->lchild;
    }else{
      q=NULL;
    }
  }
  return q;
}

五、求二叉树的带权路径长度(WPL)

//递归
int WPL=0;
void weight(BiTree bt,int level){
  if(!bt->lchild&&bt->rchild){
    WPL+=bt->data*level;
  }
  if(bt->lchild){
    weight(bt->lchild,level+1);
  }
  if(bt->rchild){
    weight(bt->rchild,level+1);
  }
}
//非递归
int weight(BiTree bt){
  if(!bt) return 0;
  BiTree p=bt,Queue[Max];
  int front=-1,rear=0,last=0,level=0,wpl=0;
  Queue[0]=p;
  while(front<rear){
    p=Queue[++front];
    if(!p->lchild&&!p->rchild){
      wpl+=level*p->data;
    }
    if(p->lchild){
      Queue[++rear]=p->lchild;
    }
    if(p->rchild){
      Queue[++rear]=p->rchild;
    }
    if(front==last){
      level++;
      last=rear;
    }
  }
  return wpl;  
}

六、将表达式树(二叉树)转换为等价的中缀表达式

void BtreeToExp(BiTree root,int deep){
  if(!root) return;
  else if(!root->lchild&&!root->rchild){
    printf(root->data);
  }else{
    if(deep>1)printf("(");
    BtreeToExp(root->lchild,deep+1);
    printf(root->data);
    BtreeToExp(root->rchild,deep+1);
    if(deep>1) printf(")");
  }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值