数据结构系列17 - 后序线索二叉树 - C语言实现

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
/*************************************************************************
* File Name: postThreadTree.c
* Author: TyrantLucifer
* E-mail: TyrantLucifer@gmail.com
* Blog: https://tyrantlucifer.com
* Created Time: Wed 07 Jul 2021 09:14:08 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>

typedef struct TreeNode {
char data;
struct TreeNode* lchild;
struct TreeNode* rchild;
struct TreeNode* parent;
int ltag;
int rtag;
}TreeNode;

void createTree(TreeNode** T, char* data, int* index, TreeNode* parent) {
char ch;
ch = data[*index];
*index += 1;
if (ch == '#') {
// 此时为空节点
*T = NULL;
}
else {
// 此时不为空
*T = (TreeNode*)malloc(sizeof(TreeNode));
(*T) -> data = ch;
(*T) -> ltag = 0;
(*T) -> rtag = 0;
(*T) -> parent = parent;
// 创建左子树,逻辑一致,进行递归
createTree(&((*T)->lchild), data, index, *T);
// 创建右子树,逻辑一致,进行递归
createTree(&((*T)->rchild), data, index, *T);
}
}

void postThreadTree(TreeNode* T, TreeNode** pre) {
if (T) {
postThreadTree(T -> lchild, pre);
postThreadTree(T -> rchild, pre);
// do something
if (T -> lchild == NULL) {
T -> ltag = 1;
T -> lchild = *pre;
}
if (*pre != NULL && (*pre) -> rchild == NULL) {
(*pre) -> rtag = 1;
(*pre) -> rchild = T;
}
*pre = T;
}
}

TreeNode* getFirst(TreeNode* T) {
while (T -> ltag == 0)
T = T -> lchild;
if (T -> rtag == 0) {
return getFirst(T -> rchild);
}
return T;
}

TreeNode* getNext(TreeNode* node) {
if (node -> rtag == 1)
return node -> rchild;
else {
// 如果是根节点
if (node -> parent == NULL) {
return NULL;
}
// 如果是右孩子
else if (node -> parent -> rchild == node) {
return node -> parent;
}
// 如果是左孩子
else {
if (node -> parent -> ltag == 0) {
return getFirst(node -> parent -> rchild);
}
else {
return node -> parent;
}
}
}
}

int main(int argc, char* argv[]) {
TreeNode* T;
TreeNode* pre = NULL;
int index = 0;
createTree(&T, argv[1], &index, NULL);
postThreadTree(T, &pre);
for (TreeNode* node = getFirst(T); node != NULL; node = getNext(node)) {
printf("%c ", node -> data);
}
printf("\n");
return 0;
}