#include<iostream>
using namespace std;
typedef char ElemType;
#define END '#'
typedef enum
{
LINK = 0,
THREAD = 1
}PointerTag;
typedef struct BiThrNode //定义二叉树节点
{
BiThrNode *leftchild;
BiThrNode *rightchild;
PointerTag Ltag, Rtag;
ElemType data;
}BiThrNode,*BinaryThreadTree;
BiThrNode *Buynode()
{
BiThrNode *s = (BiThrNode*)malloc(sizeof(BiThrNode));
if(NULL == s) exit(1);
memset(s,0,sizeof(BiThrNode));
return s;
}
void Freenode(BiThrNode *p)
{
free(p);
}
BiThrNode * CreateTree2(ElemType *&str) //创建二叉树
{
BiThrNode *s = NULL;
if(*str != END)
{
s = Buynode();
s->data = *str;
s->leftchild = CreateTree2(++str);
s->rightchild = CreateTree2(++str);
}
return s;
}
void InOrder(BiThrNode *p)
{
if(p != NULL)
{
InOrder(p->leftchild);
cout<<p->data<<" ";
InOrder(p->rightchild);
}
}
void MakeThread(BiThrNode *p,BiThrNode *&ptr)
{
if(p != NULL)
{
MakeThread(p->leftchild,ptr);
if(p->leftchild == NULL)
{
p->leftchild = ptr;
p->Ltag = THREAD;
}
if(ptr != NULL && ptr->rightchild == NULL)
{
ptr->rightchild = p;
ptr->Rtag = THREAD;
}
ptr = p;
MakeThread(p->rightchild,ptr);
}
}
void MakeThreadTree(BiThrNode *p) //创建线索二叉树
{
BiThrNode *ptr = NULL;
MakeThread(p,ptr);
ptr->rightchild = NULL;
ptr->Rtag = THREAD;
}
BiThrNode * First(BiThrNode *ptr)
{
while(ptr != NULL && ptr->Ltag != THREAD)
{
ptr = ptr->leftchild;
}
return ptr;
}
BiThrNode *Next(BiThrNode *ptr)
{
if(NULL == ptr) return NULL;
if(ptr->Rtag == THREAD)
{
return ptr->rightchild;
}
else
{
return First(ptr->rightchild);
}
}
BiThrNode *Last(BiThrNode *ptr)
{
while(ptr != NULL && ptr->Rtag != THREAD)
{
ptr = ptr->rightchild;
}
return ptr;
}
BiThrNode *Prev(BiThrNode *ptr)
{
if(NULL == ptr) return NULL;
if(ptr->Ltag == THREAD)
{
return ptr->leftchild;
}
else
{
return Last(ptr->leftchild);
}
}
void InOrderThread(BiThrNode *ptr) //线索二叉树的中序遍历
{
for(BiThrNode *p = First(ptr); p != NULL; p = Next(p))
{
cout<<p->data<<" ";
}
cout<<endl;
}
void ResInOrderThread(BiThrNode *ptr) //二叉树反转
{
for(BiThrNode *p = Last(ptr); p != NULL; p = Prev(p))
{
cout<<p->data<<" ";
}
cout<<endl;
}
int main()
{
ElemType *ar="ABC##DE##F##G#H##";
BinaryThreadTree root =NULL;
root = CreateTree2(ar);
InOrder(root); //中序遍历,C B E D F A G H
cout<<endl;
MakeThreadTree(root); //创建线索二叉树
InOrderThread(root); //线索二叉树的中序遍历, C B E D F A G H
ResInOrderThread(root); //二叉树反转 H G A F D E B C
return 0;
}