#define _CRT_SECURE_NO_WARNINGS 1
//线索二叉树
#include <stdio.h>
#include <stdlib.h>
typedef enum{Link,Thread} PointerTag;
typedef struct BiThrNode
{
char data;
struct BiThrNode* lchild, * rchild;
PointerTag LTag;
PointerTag RTag;
}BiThrNode,*BiThrTree;
//创建
void CreateBiTree(BiThrTree* T)
{
char ch;
scanf("%c", &ch);
if (ch == '#')
*T = NULL;
else
{
*T = (BiThrTree)malloc(sizeof(BiThrNode));
(*T)->data = ch;
(*T)->LTag = Link;
(*T)->RTag = Link;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
//线索化
BiThrTree pre;
void InThreading(BiThrTree T)
{
if (T)
{
InThreading(T->lchild);
if (!T->lchild)
{
T->LTag = Thread;
T->lchild = pre;
}
if (!(pre)->rchild)
{
(pre)->RTag = Thread;
(pre)->rchild = T;
}
pre = T;
InThreading(T->rchild);
}
}
void InOrderThreading(BiThrTree* p, BiThrTree T)
{
*p = (BiThrTree)malloc(sizeof(BiThrNode));
(*p)->LTag = Link;
(*p)->RTag = Thread;
(*p)->rchild = *p;
if (!T)
{
(*p)->lchild = *p;
}
else
{
(*p)->lchild = T;
pre = *p;
InThreading(T);
pre->rchild = *p;
pre->RTag = Thread;
(*p)->rchild = pre;
}
}
//遍历线索二叉树
void InOrderTraverse(BiThrTree T)
{
BiThrTree 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;
}
}
int main()
{
BiThrTree T,p;
printf("创建线索二叉树: \n");
CreateBiTree(&T);
InOrderThreading(&p, T);
printf("中序遍历结果: ");
InOrderTraverse(p);
return 0;
}