forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
94.c
101 lines (86 loc) · 2.12 KB
/
94.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
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct StackNode {
struct TreeNode *val;
struct StackNode *next;
};
struct Stack {
struct StackNode *top_pt;
int size;
};
void push(struct Stack *stack, struct TreeNode *new_data) {
if (stack) {
struct StackNode *new_node
= (struct StackNode *)calloc(1, sizeof(struct StackNode));
new_node->val = new_data;
new_node->next = stack->top_pt;
stack->top_pt = new_node;
stack->size++;
}
}
struct TreeNode* top(struct Stack stack) {
if (stack.top_pt) {
return stack.top_pt->val;
}
else return NULL;
}
void pop(struct Stack *stack) {
if (stack && stack->top_pt) {
struct StackNode *top = stack->top_pt;
stack->top_pt = top->next;
stack->size--;
free(top);
}
}
int *inorderTraversal(struct TreeNode *root, int *returnSize) {
*returnSize = 0;
if (root == NULL) return NULL;
struct Stack stack;
stack.top_pt = NULL;
stack.size = 0;
int *ret = (int *)calloc(1024, sizeof(int));
struct TreeNode *p = root;
while (stack.size || p) {
if (p) {
push(&stack, p);
p = p->left;
}
else {
p = top(stack);
pop(&stack);
ret[(*returnSize)++] = p->val;
p = p->right;
}
}
return ret;
}
int main() {
struct TreeNode *t = (struct TreeNode *)calloc(5, sizeof(struct TreeNode));
struct TreeNode *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;
int size = 0;
int *ret = inorderTraversal(p, &size);
int i;
/* should be 12345 */
for (i = 0; i < size; i++) {
printf("%d", ret[i]);
}
printf("\n");
return 0;
}