数据结构系列16-先序线索二叉树

数据结构系列16 - 先序线索二叉树 - 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
/*************************************************************************
* File Name: preThreadTree.c
* Author: TyrantLucifer
* E-mail: TyrantLucifer@gmail.com
* Blog: https://tyrantlucifer.com
* Created Time: Wed 07 Jul 2021 09:14:08 PM CST
************************************************************************/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

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

void createTree(TreeNode** T, char* data, int* index) {
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;
// 创建左子树,逻辑一致,进行递归
createTree(&((*T)->lchild), data, index);
// 创建右子树,逻辑一致,进行递归
createTree(&((*T)->rchild), data, index);
}
}

void preThreadTree(TreeNode* T, TreeNode** pre) {
if (T) {
if (T -> lchild == NULL) {
T -> ltag = 1;
T -> lchild = *pre;
}
if (*pre != NULL && (*pre) -> rchild == NULL) {
(*pre) -> rtag = 1;
(*pre) -> rchild = T;
}
*pre = T;
if (T -> ltag == 0)
preThreadTree(T -> lchild, pre);
preThreadTree(T -> rchild, pre);
}
}

TreeNode* getNext(TreeNode* node) {
if (node -> rtag == 1 || node -> ltag == 1)
return node -> rchild;
else
return node -> lchild;
}

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

数据结构系列16-先序线索二叉树

https://tyrantlucifer.com/40.html

发布于

2021-07-13

更新于

2021-07-13

许可协议

评论

:D 一言句子获取中...