数据结构基础11-线索二叉树的三种写法

一.中序线索二叉树

1.代码如下:

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
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

typedef struct BiThrNode {
char data;// 数据
struct BiThrNode* leftchild;// 左指针
struct BiThrNode* rightchild;// 右指针
int LTag; // 左标志
int RTag; // 右标志
}BiThrNode, * BiThrTree;
// 全局定义一个线索化二叉树的一个全局变量
BiThrNode* pre = NULL;
// 二叉树的创建
void createTree(BiThrTree& app) {
char ch;
cin >> ch;
if (ch == '#') {
app = NULL;
}
else {
app = new BiThrNode;
app->data = ch;
app->LTag = 0;
app->RTag = 0;
createTree(app->leftchild);
createTree(app->rightchild);
}
}
// 线索化中序二叉树
void middleTree(BiThrTree &app) {
if (app) {
middleTree(app->leftchild);
// 在这里写一些线索化的代码
if (!app->leftchild) {// 如果左子树为空,线索化左子树
app->LTag = 1;
app->leftchild = pre;
}
if (pre != NULL && pre->rightchild == NULL) { // 如果pre的右子树为空的话,线索化最下面的这个节点前驱后继之类
pre->RTag = 1;
pre->rightchild = app;
}
pre = app;
middleTree(app->rightchild);
}
}
// 下面就是遍历线索化中序二叉树的方法
void middleprintf(BiThrTree& app) {
BiThrNode* current = app;
while (current && current->LTag == 0) {
current = current->leftchild;
}
while (current) {
cout << current->data << "---";
if (current->RTag == 1) {
current = current->rightchild;
}
else {
current = current->rightchild;
while (current && current->LTag == 0) {
current = current->leftchild;
}
}
}
}
int main() {
BiThrTree app;
createTree(app);
middleTree(app);
cout << "线索化中序二叉树的遍历为:";
middleprintf(app);
cout << "end" << endl;
return 0;
}

2.参考数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
A
B
C
#
#
D
#
#
E
F
#
#
G
#
#

3.参考结果:

1
线索化中序二叉树的遍历为:C---B---D---A---F---E---G---end

二.先序线索二叉树

1.代码如下:

1

2.参考数据:

1

3.参考结果:

1

三.后序线索二叉树

1.代码如下:

1

2.参考数据:

1

3.参考结果:

1