#include <stdio.h>
#include <stdlib.h>
typedef char TElemType;
typedef enum {Link,Thread} pointertag;
typedef struct TBTNode TBTNode;//结构体类型
typedef TBTNode *BiThrTree;//结构体指针类型
struct TBTNode
{
TElemType data;
BiThrTree lchild;
BiThrTree rchild;
pointertag ltag;
pointertag rtag;
};
BiThrTree CreateBiThrTree(BiThrTree T);//创建普通树
BiThrTree CreateThread(TBTNode *b);//对创建好的二叉树进行线索化
void Thead(TBTNode *p);//递归线索化
void ThInOrder(TBTNode *tb);//以找线索的方式中序遍历
void Print(BiThrTree T);//正常的中序遍历
BiThrTree pre;//全局变量,指向上一个访问的节点,用来在线索化的时候记录前驱的
int main()
{
BiThrTree T = NULL;
T = CreateBiThrTree(T);
/*创建树的测试用例:ABC##DE#G##F### 就是书上131页算法6.3那里的测试数据,树的图在127页左下角*/
BiThrTree Th = CreateThread(T);
ThInOrder(Th);
return 0;
}
BiThrTree CreateBiThrTree(BiThrTree T)
{
TElemType ch;
scanf("%c",&ch);
if(ch=='#')
{
return NULL;
}
else
{
T=(TBTNode *)malloc(sizeof(TBTNode));
T->data = ch;
T->ltag = T->rtag = Link;
T->lchild = CreateBiThrTree(T->lchild);
T->rchild = CreateBiThrTree(T->rchild);
return T;
}
}
BiThrTree CreateThread(TBTNode *b)
{
TBTNode *root;
root=(TBTNode *)malloc(sizeof(TBTNode));
root->ltag=Link;
root->rtag=Thread;
root->rchild=b;
if(b==NULL) root->lchild=root;
else
{
root->lchild=b;
pre=root;
Thead(b);
pre->rchild=root;
pre->rtag=Thread; //你这里打成了ltag,调试了好久。。。
root->rchild=pre;
}
return root;
}
void Thead(TBTNode *p)
{
if(p!=NULL)
{
Thead(p->lchild);
if(p->lchild==NULL)
{
p->lchild=pre;
p->ltag=Thread;
}
else p->ltag=Link;
if(pre->rchild==NULL)
{
pre->rchild=p;
pre->rtag=Thread;
}
else pre->rtag=Link;
pre=p;
Thead(p->rchild);
}
}
void ThInOrder(TBTNode *tb)
{
TBTNode *p=tb->lchild;
while(p!=tb)
{
while(p->ltag==Link) p=p->lchild;
printf("%c ",p->data);
while(p->rtag==Thread&&p->rchild!=tb)
{
p=p->rchild;
printf("%c ",p->data);
}
p=p->rchild;
}
}
void Print(BiThrTree T)
{
if (T) {
Print(T->lchild);
printf("%c",T->data);
Print(T->rchild);
}
}