线索树

最近懒了,贴篇源码补补空闲……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
using namespace std;
typedef struct bithrnode
{
char data;
struct bithrnode *lchild;
struct bithrnode *rchild;
int ltag, rtag;
}BiThrNode, *BiThrTree;

BiThrTree pre;

void InitBTree(BiThrTree &BT);
void CreatBTree(BiThrTree &BT);
void AddThread(BiThrTree p);
void ThreadTree(BiThrTree BT, BiThrTree &head);
BiThrTree InorderNext(BiThrTree p);
void ThInorder(BiThrTree head);

void InitBTree(BiThrTree &BT)
{
BT = NULL;
}


void CreatBTree(BiThrTree &BT)
{
char ch;
ch = getchar();
if (ch == ' ')
BT = NULL;
else
{
BT = new BiThrNode;
BT->data = ch;
BT->ltag = 0;
BT->rchild = 0;
CreatBTree(BT->lchild);
CreatBTree(BT->rchild);
}
}



void ThreadTree(BiThrTree BT, BiThrTree &head)
{
head = new BiThrNode;
head->data = NULL;
head->ltag = 0;
head->rtag = 0;
head->rchild = head;
if (BT == NULL)
head->lchild = head;
else
{
pre = head;
head->lchild = BT;
AddThread(BT);
pre->rchild = head;
pre->rtag = 1;
head->rchild = pre;
head->rtag = 1;
}
}


void AddThread(BiThrTree p)
{
if (p != NULL)
{
AddThread(p->lchild);
if (p->lchild == NULL)
{
p->ltag = 1;
p->lchild = pre;
}
if (pre->rchild == NULL)
{
pre->rtag = 1;
pre->rchild = p;
}
pre = p;
AddThread(p->rchild);
}
}


BiThrTree InorderNext(BiThrTree p)
{
if (p->rtag == 1)
return p->rchild;
else
{
p = p->rchild;
while (p->ltag == 0)
p = p->lchild;
return p;
}
}


void ThInorder(BiThrTree head)
{
BiThrTree HT;
HT = head->lchild;
while (HT != head)
if (HT != NULL)
{
while (HT->ltag == 0)
HT = HT->lchild;
while (HT != head)
{
cout << HT->data << ' ';
HT = InorderNext(HT);
}
}
}
void main()
{
BiThrTree T, head;
InitBTree(T);
cout << "InitTree completed!" << endl;
cout << "Create Tree:" << endl;
CreatBTree(T);
ThreadTree(T, head);
cout << "The ThreadTree is Inordered:" << endl;
ThInorder(head);
system("pause");
}
作者

Wu Rang

发布于

2010-07-01

更新于

2024-06-13

许可协议

评论