//首先创建一个二叉树,对该树线索化,对该树线索化遍历
#include<stdio.h>
#include<malloc.h>
#define ElemType char
typedef enum tag{link,thread};
typedef struct threadtree
{
ElemType data;
struct threadtree *lchild,*rchild;
tag ltag,rtag;
}threadtree,*sthreadtree;
//全局变量
sthreadtree pre;
//建立二叉树,类似先序遍历
void creat(sthreadtree &t)
{
char ch;
scanf("%c",&ch);
if(ch=='#')
t=NULL;
else
{
t=(sthreadtree)malloc(sizeof(threadtree));
t->data=ch;
t->ltag=link;t->rtag=link;
creat(t->lchild);
creat(t->rchild);
}
}
//中序遍历
void mid(sthreadtree t)
{
if(t)
{
mid(t->lchild);
printf("%c",t->data);
mid(t->rchild);
}
}
//线索化二叉树,类似中序遍历
void InThread(sthreadtree t)
{
if(t)
{
InThread(t->lchild);
if(!t->lchild) {t->ltag=thread;t->lchild=pre;}
if(!pre->rchild) {pre->rtag=thread;pre->rchild=t;}
pre=t;
InThread(t->rchild);
}
}
//添加一个头结点
void InorderThread(sthreadtree &head,sthreadtree t)
{
//sthreadtree pre;
head=(sthreadtree)malloc(sizeof(threadtree));
head->ltag=link;head->rtag=thread;
head->rchild=head;
if(!t) head->lchild=head;
else
{
head->lchild=t;pre=head;
InThread(t);
pre->rchild=head;pre->rtag=thread;
head->rchild=pre;
}
}
//线索化遍历二叉树
void InOrderTraverse(sthreadtree t)
{
sthreadtree p;
p=t->lchild;
while(p!=t)
{
while(p->ltag==link) p=p->lchild;
printf("%c",p->data);
while(p->rtag==thread&&p->rchild!=t)
{
p=p->rchild;
printf("%c",p->data);
}
p=p->rchild;
}
}
void main()
{
sthreadtree t=NULL;
sthreadtree T=NULL;//head
printf("请输入要建立树的序列:/n");
creat(t);//mid(t);printf("/n");
InorderThread(T,t);
InOrderTraverse(T);
printf("/n");
}
/*
请输入要建立树的序列:
HDA##C#B##GF#E###
ADCBHFEG
Press any key to continue
*/