数据结构(C语言版)规范代码之树(2线索化)

//先序建树-+a##*b##-c##d##/e##f##
#include<iostream>
#include<malloc.h>
using namespace std;
#define Status int
#define TElemType char
#define OVERFLOW 0
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef enum PointerTag{Link=0,Thread};//Link==0:指针,Thread==1: 线索
typedef struct BiThrNode//树结点
{
 TElemType data;//数据域
 struct BiThrNode *lchild,*rchild;//指针域
 PointerTag LTag,RTag;//左右标志位
}BiThrNode,*BiThrTree;
Status CreateBiTree(BiThrTree &T);
void InThreading(BiThrTree p,BiThrTree &pre);//线索化
Status InOrderThreading(BiThrTree &Thrt ,BiThrTree T);
Status InOrderTraverse_Thr(BiThrTree T,Status (*Visite)(TElemType e));
Status Visite(TElemType e);
Status Next_Thr(BiThrTree t,BiThrTree &p,BiThrTree Thrt);//
Status InOrderTraverse(BiThrTree T,BiThrTree Thrt);
void main()
{
 cout<<"先序建树:";
 BiThrTree T;
 CreateBiTree(T);
 BiThrTree Thrt;
 InOrderThreading(Thrt,T);
 InOrderTraverse_Thr(Thrt,Visite);
// InOrderTraverse(T,Thrt);
 cout<<endl;
}
Status Visite(TElemType e)
{
 cout<<e;
 return OK;
}
Status CreateBiTree(BiThrTree &T) {
//构造二叉链表表示的二叉树T
 char ch;
 cin>>ch;
 if(ch=='#')
 {
  T=NULL;
 }
 else
 {
  T=(BiThrTree)malloc(sizeof(BiThrNode));
  T->data=ch;
  CreateBiTree(T->lchild);
  CreateBiTree(T->rchild);
 }
 return OK;
}
Status InOrderThreading(BiThrTree &Thrt,BiThrTree T)
{
 BiThrTree pre;
 if(!(Thrt=(BiThrTree)malloc(sizeof(BiThrNode)))) exit(0);
 Thrt->LTag=Link;
 Thrt->RTag=Thread;
 Thrt->lchild=Thrt;
 if(!T)
  Thrt->lchild=T;
 else
 {
  Thrt->lchild=T;
  pre=Thrt;
  InThreading(T,pre);
  pre->rchild=Thrt;
  pre->RTag=Thread;
  Thrt->rchild=pre;
 }
 return OK;
}
void InThreading(BiThrTree p,BiThrTree &pre)
{
 if(p)
 {
  InThreading(p->lchild,pre);//左子树线索化
  if(!p->lchild)
  {
   p->LTag=Thread;
   p->lchild=pre;
  }//前驱线索
  if(!pre->rchild)
  {
   pre->RTag=Thread;
   pre->rchild=p;
  }//后驱线索
  pre=p;
  InThreading(p->rchild,pre);
 }
}
Status InOrderTraverse_Thr(BiThrTree T,Status(*Visite)(TElemType e))//遍历
{
 BiThrTree p;
 p=T->lchild;
 while(p!=T)
 {
  while(p->LTag==Link)
   p=p->lchild;
  if(!Visite(p->data))
   return ERROR;
  while(p->RTag==Thread&&p->rchild!=T)
  {
   p=p->rchild;
   Visite(p->data);
  }
  p=p->rchild;
 }
 return OK;
}
Status Next_Thr(BiThrTree T,BiThrTree &p,BiThrTree Thrt) //求后继节点
{
 p=T->rchild;
 if(p==Thrt)
  return ERROR;
 if(T->RTag==Link) 
 while(p->LTag==Link)
 {
  p=p->lchild;
 }
 return OK;
}
Status InOrderTraverse(BiThrTree T,BiThrTree Thrt)
{

 BiThrTree p;
 while(p)
 {
  Next_Thr(T,p,Thrt);
  cout<<p->data;
 }
 return OK;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值