- Notifications
You must be signed in to change notification settings - Fork 117
/
Copy path145.c
107 lines (92 loc) · 2.31 KB
/
145.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
#include<stdio.h>
#include<stdlib.h>
structTreeNode {
intval;
structTreeNode*left;
structTreeNode*right;
};
structStackNode {
structTreeNode*val;
structStackNode*next;
};
structStack {
structStackNode*top_pt;
intsize;
};
voidpush(structStack*stack, structTreeNode*new_data) {
if (stack) {
structStackNode*new_node
= (structStackNode*)calloc(1, sizeof(structStackNode));
new_node->val=new_data;
new_node->next=stack->top_pt;
stack->top_pt=new_node;
stack->size++;
}
}
structTreeNode*top(structStackstack) {
if (stack.top_pt) {
returnstack.top_pt->val;
}
elsereturnNULL;
}
voidpop(structStack*stack) {
if (stack&&stack->top_pt) {
structStackNode*top=stack->top_pt;
stack->top_pt=top->next;
stack->size--;
free(top);
}
}
int*postorderTraversal(structTreeNode*root, int*returnSize) {
*returnSize=0;
if (root==NULL) returnNULL;
structStackstack;
stack.top_pt=NULL;
stack.size=0;
int*ret= (int*)calloc(1024, sizeof(int));
structTreeNode*p=root;
structTreeNode*last=NULL;
while (stack.size||p) {
if (p) {
push(&stack, p);
p=p->left;
}
else {
structTreeNode*t=top(stack);
if (t->right&&last!=t->right) {
p=t->right;
}
else {
pop(&stack);
ret[(*returnSize)++] =t->val;
last=t;
}
}
}
returnret;
}
intmain() {
structTreeNode*t= (structTreeNode*)calloc(5, sizeof(structTreeNode));
structTreeNode*p=t;
p->val=4;
p->left=++t;
t->val=2;
p->left->left=++t;
t->val=1;
t->left=t->right=NULL;
p->left->right=++t;
t->val=3;
t->left=t->right=NULL;
p->right=++t;
t->val=5;
t->left=t->right=NULL;
intsize=0;
int*ret=postorderTraversal(p, &size);
inti;
/* should be 13254 */
for (i=0; i<size; i++) {
printf("%d", ret[i]);
}
printf("\n");
return0;
}