数据结构系列13 - 二叉树的非递归(先序+中序)遍历 - 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
105
106
107
108
109
110
111
112
113
114
115
116
/*************************************************************************
* File Name: treeNonRecursive.c
* Author: TyrantLucifer
* E-mail: TyrantLucifer@gmail.com
* Blog: https://tyrantlucifer.com
* Created Time: Sun 16 May 2021 05:51:25 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode {
char data;
struct TreeNode* lchild;
struct TreeNode* rchild;
}TreeNode;

typedef struct StackNode {
TreeNode* data;
struct StackNode* next;
}StackNode;

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

StackNode* initStack() {
StackNode* S = (StackNode*)malloc(sizeof(StackNode));
S->data = NULL;
S->next = NULL;
return S;
}

void push(TreeNode* data, StackNode* S) {
StackNode* node = (StackNode*)malloc(sizeof(StackNode));
node->data = data;
node->next = S->next;
S->next = node;
}

int isEmpty(StackNode* S) {
if (S->next == NULL) {
return 1;
}
else {
return 0;
}
}

StackNode* pop(StackNode* S) {
if (isEmpty(S)) {
return NULL;
}
else {
StackNode* node = S->next;
S->next = node->next;
return node;
}
}

void preOrder(TreeNode* T) {
TreeNode* node = T;
StackNode* S = initStack();
while (node || !isEmpty(S)) {
if (node) {
printf("%c ", node->data);
push(node, S);
node = node->lchild;
}
else {
node = pop(S) -> data;
node = node->rchild;
}
}
}

void inOrder(TreeNode* T) {
TreeNode* node = T;
StackNode* S = initStack();
while (node || !isEmpty(S)) {
if (node) {
push(node, S);
node = node->lchild;
}
else {
node = pop(S) -> data;
printf("%c ", node->data);
node = node->rchild;
}
}
}

int main(int argc, char* argv[]) {
TreeNode* T;
int index = 0;
createTree(&T, argv[1], &index);
preOrder(T);
printf("\n");
inOrder(T);
printf("\n");
return 0;
}