/*
线索二叉树中序不带头结点的遍历
输出结果:
ABDF##G###C#E##
中序遍历线索二叉树:F D G B A C E
中序遍历线索二叉树逆序:E C A B G D F
请按任意键继续. . .
*/
# include <stdio.h>
# include <stdlib.h>
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");
}