#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef enum {
Link,
Thread
} PointerTag;
typedef struct BiThrNode {
ElemType data;
struct BiThrNode *lchild, *rchild;
PointerTag Ltag, Rtag;
} BiThrNode, *BiThrTree;
BiThrTree pre = NULL;
bool CreateBiThrTree(BiThrTree &T) {
ElemType ch;
scanf("%c", &ch);
getchar();
if (ch == ' ') {
T = NULL;
} else {
if (!(T = (BiThrTree) malloc(sizeof(BiThrNode)))) {
return false;
}
T->data = ch;
printf("请输入%c的左子树:", ch);
CreateBiThrTree(T->lchild);
printf("请输入%c的右子树:", ch);
CreateBiThrTree(T->rchild);
}
return true;
}
void Visit(BiThrTree T) {
printf("%c ", T->data);
}
void OrderThreading(BiThrTree &T) {
if (!T->lchild) {
T->Ltag = Thread;
T->lchild = pre;
}
if (pre && !pre->rchild) {
pre->Rtag = Thread;
pre->rchild = T;
}
pre = T;
}
void InOrder(BiThrTree T) {
if (T) {
InOrder(T->lchild);
Visit(T);
OrderThreading(T);
InOrder(T->rchild);
}
}
void InOrderThraverse_Thr(BiThrTree T) {
while (T) {
while (T->Ltag == Link) {
T = T->lchild;
}
Visit(T);
while (T->Rtag == Thread && T->rchild != NULL) {
T = T->rchild;
Visit(T);
}
T = T->rchild;
}
}
BiThrNode *InLastNode(BiThrNode *p) {
while (p->Rtag == Link)
p = p->rchild;
return p;
}
BiThrNode *InPreNode(BiThrNode *p) {
if (p->Ltag == Link)
return InLastNode(p->lchild);
else
return p->lchild;
}
void ReInOderThraverse_Thr(BiThrNode *T) {
for (BiThrNode *p = InLastNode(T); p != NULL; p = InPreNode(p)) {
Visit(p);
}
}
void CreatThread(BiThrTree T) {
if (T) {
InOrder(T);
if (!pre->rchild)
pre->Rtag = Thread;
}
}
int main() {
BiThrTree T;
printf("请先输入树根结点(空格代表空结点):");
CreateBiThrTree(T);
printf("\n");
printf("直接中序遍历二叉树的结果为:");
CreatThread(T);
printf("\n\n");
printf("正向遍历中序线索二叉树请输入 1\n");
printf("逆向遍历中序线索二叉树请输入 2\n");
printf("请选择是采用正向还是逆向输出:");
int id;
scanf("%d", &id);
if (id == 1) {
printf("正向遍历中序线索二叉树的结果为:");
InOrderThraverse_Thr(T);
}
if (id == 2) {
printf("逆向遍历中序线索二叉树的结果为:");
ReInOderThraverse_Thr(T);
}
printf("\n");
return 0;
}