//先序建树-+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;
}