# include
# include
typedef enum {link, Thread} PointerTag;//link为0表示有左右孩子结点,Thread为1表示设置前驱或者后继结点
# define ElemType char
typedef struct BiThrNode{
ElemType data;
struct BiThrNode * lchild, * rchild;
PointerTag lTag, rTag;
}BiThrNode, *BiThrTree;
void CreateBiThrTree(BiThrTree * proot);//创建二叉树
void InOrderThreading(BiThrTree root);//中序线索化二叉树
BiThrTree FindNext(BiThrTree p);//寻找后继结点
void InOrderTree(BiThrTree root);//中序遍历线索二叉树
BiThrTree FindPrecursor(BiThrTree p);//寻找前驱结点
void ReverseInOrderTree(BiThrTree root);//中序遍历线索二叉树逆序
int main(void)
{
BiThrTree root;
CreateBiThrTree(&root);
InOrderThreading(root);
printf("中序遍历线索二叉树:");
InOrderTree(root);
printf("中序遍历线索二叉树逆序:");
ReverseInOrderTree(root);
system("pause");
return 0;
}
void CreateBiThrTree(BiThrTree * proot)//创建线索二叉树
{
ElemType elem;
scanf("%c", &elem);
if('#' == elem)
*proot = NULL;
else
{
*proot = (BiThrTree)malloc(sizeof(BiThrNode));
if(NULL == *proot)
exit(-1);
(*proot)->data = elem;
CreateBiThrTree(&(*proot)->lchild);
if((*proot)->lchild)
(*proot)->lTag = link;
CreateBiThrTree(&(*proot)->rchild);
if((*proot)->rchild)
(*proot)->rTag = link;
}
}
void InOrderThreading(BiThrTree root)//中序线索化二叉树
{
if(NULL == root)
return;
static BiThrTree pre;//定义局部静态变量pre保存当前结点的前驱结点位置,也可定义为全局变量
BiThrTree p = root;
InOrderThreading(p->lchild);
if(!p->lchild)
{
p->lTag = Thread;
p->lchild = pre;
}
if(pre && !pre->rchild)
{
pre->rTag = Thread;
pre->rchild = p;
}
pre = p;
InOrderThreading(p->rchild);
}
BiThrTree FindNext(BiThrTree p)//寻找后继结点
{
BiThrTree Next;
if(Thread == p->rTag)
Next = p->rchild;
else
{
Next = p->rchild;
while(link == Next->lTag)
Next = Next->lchild;
}
return Next;
}
void InOrderTree(BiThrTree root)//中序遍历线索二叉树
{
if(NULL == root)
return;
BiThrTree p = root;
while(link == p->lTag)
p = p->lchild;
printf("%c ", p->data);
while(p->rchild)
{
p = FindNext(p);
printf("%c ", p->data);
}
printf("n");
}
BiThrTree FindPrecursor(BiThrTree p)//寻找前驱结点
{
BiThrTree Prec;
if(Thread == p->lTag)
Prec = p->lchild;
else
{
Prec = p->lchild;
while(link == Prec->rTag)
Prec = Prec->rchild;
}
return Prec;
}
void ReverseInOrderTree(BiThrTree root)//中序遍历线索二叉树逆序
{
if(NULL == root)
return;
BiThrTree p = root;
while(link == p->rTag)
p = p->rchild;
printf("%c ", p->data);
while(p->lchild)
{
p = FindPrecursor(p);
printf("%c ", p->data);
}
printf("n");
}



