-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary Tree Zigzag Level Order Traversal
74 lines (70 loc) · 2.14 KB
/
Binary Tree Zigzag Level Order Traversal
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
struct TreeQueue {
struct TreeNode * node;
struct TreeQueue * next;
int level;
};
int** zigzagLevelOrder(struct TreeNode* root, int* returnSize, int** returnColumnSizes){
if (root == NULL){
*returnSize = 0;
return NULL;
}
struct TreeQueue * start, *end;
struct TreeQueue * node = malloc(sizeof(struct TreeQueue));
node->node = root;
node->next = NULL;
node->level = 0;
start = node;
end = node;
int next_level = 1;
int ** result = malloc(sizeof(int *) * 1000);
int i = 0;
int cur_num, this_level;
struct TreeQueue * l, * r;
int j, num;
int save;
*returnSize = 0;
*returnColumnSizes = (int *)malloc(sizeof(int) * 1000);
while (1){
(*returnColumnSizes)[*returnSize] = next_level;
*returnSize = *returnSize + 1;
cur_num = next_level;
next_level = 0;
int save;
this_level = start->level;
result[this_level] = malloc(sizeof(int) * cur_num);
for (i = 0; i < cur_num; i++){
result[this_level][i] = start->node->val;
if (start->node->left != NULL){
l = malloc(sizeof(struct TreeQueue));
l->node = start->node->left;
l->next = NULL;
l->level = start->level + 1;
next_level++;
end->next = l;
end = end->next;
}
if (start->node->right != NULL){
r = malloc(sizeof(struct TreeQueue));
r->node = start->node->right;
r->next = NULL;
r->level = start->level + 1;
next_level++;
end->next = r;
end = end->next;
}
start = start->next;
//free(start);
}
if (next_level == 0)
break;
}
for (i = 1; i < *returnSize; i+=2){
num = returnColumnSizes[0][i];
for (j = 0; j < (returnColumnSizes[0][i] + 1) / 2; j++){
save = result[i][j];
result[i][j] = result[i][num - 1 - j];
result[i][num - 1 - j] = save;
}
}
return result;
}