数据结构系列14-二叉树的非递归后序遍历

数据结构系列14 - 二叉树的非递归(后序)遍历 - 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
117
118
/*************************************************************************
* File Name: treeNonRecursivePost.c
* Author: TyrantLucifer
* E-mail: TyrantLucifer@gmail.com
* Blog: https://tyrantlucifer.com
* Created Time: Sun 04 Jul 2021 02:24:42 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode {
char data;
struct TreeNode* lchild;
struct TreeNode* rchild;
int flag;
}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;
(*T) -> flag = 0;
// 创建左子树,逻辑一致,进行递归
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;
}
}

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

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

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

数据结构系列14-二叉树的非递归后序遍历

https://tyrantlucifer.com/38.html

发布于

2021-07-04

更新于

2021-07-04

许可协议

评论

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