1 #include <iostream>
2 #include <stdio.h>
3 using namespace std;
4
5 typedef char Elemtype;
6
7 typedef struct ThreadNode{
8 Elemtype data;
9 struct ThreadNode *lchild,*rchild;
10 int ltag,rtag; //左右标签,为0代表有孩子,为1代表没有孩子
11 }*ThreadTree;
12
13 //中序线索化操作
14 void InThread(ThreadTree &p,ThreadTree &pre){
15 if(p != NULL){
16 InThread(p->lchild,pre); //递归左子树
17 if(p->lchild == NULL){
18 p->lchild = pre; //左链指向中序遍历的前驱结点
19 p->ltag = 1;
20 }
21 if(pre!=NULL && pre->rchild==NULL){
22 pre->rchild = p; //指向中序遍历的后继结点
23 pre->rtag = 1;
24 }
25 pre = p;
26 InThread(p->rchild,pre); //递归右子树
27 }
28 }
29
30 //线索二叉树建立的主算法
31 void CreateThread(ThreadTree T){
32 ThreadTree pre = NULL;
33 if(T!=NULL){
34 InThread(T,pre);
35 pre->rchild = NULL; //将末尾的结点后继置空
36 pre->rtag = 1;
37 }
38 }
39
40 //线索二叉树的遍历
41 ThreadNode *FirstNode(ThreadNode *p){
42 while(p->ltag==0) p = p->lchild; //一直找到最左边的那个结点
43 return p;
44 }
45 ThreadNode *NextNode(ThreadNode *p){
46 if(p->rtag==0) return FirstNode(p->rchild); //在有右子树的情况下
47 else return p->rchild; //在没有右子树的情况下,返回后继结点
48 }
49 void InOrder(ThreadNode *T){
50 cout<<"中序遍历结果如下:"<<endl;
51 for(ThreadNode *p=FirstNode(T);p!=NULL;p=NextNode(p))
52 cout<<p->data<<" ";
53 cout<<endl;
54 }
55 //初始化结点
56 ThreadNode *CreateNode(Elemtype da){
57 ThreadNode *p = new ThreadNode();
58 p->lchild=NULL;
59 p->rchild=NULL;
60 p->ltag=0;
61 p->ltag=0;
62 p->data=da;
63 }
64
65 int main(){
66 ThreadNode *head = CreateNode('A');
67 ThreadNode *p = CreateNode('B');
68 head->lchild=p;
69 p=CreateNode('C');
70 head->rchild=p;
71 ThreadNode *t=CreateNode('D');
72 p->lchild=t;
73 t=CreateNode('E');
74 p->rchild=t;
75 //线索化
76 CreateThread(head);
77 InOrder(head);
78 }
