-
Notifications
You must be signed in to change notification settings - Fork 0
/
zigzag.cpp
105 lines (103 loc) · 1.94 KB
/
zigzag.cpp
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
#include <stdio.h>
#include <stdlib.h>
#define Max 30
/*8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1
*/
struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
int value;
int flag;
};
int inorder[Max];
int postorder[Max];
int zigzag[Max][2] = {};
int top = 0;
struct TreeNode* transform(int*inorder, int*postorder, int n, int level)
{
int i;
if (!n)return NULL;
for (i = 0; i<n; i++)
{
if (inorder[i] == *(postorder + n - 1))
break;
}
struct TreeNode* preorder = (struct TreeNode*)malloc(sizeof(struct TreeNode));
preorder->value = *(postorder + n - 1);
preorder->flag = level;
preorder->left = transform(inorder, postorder, i, (level + 1) % 2);
preorder->right = transform(inorder + i + 1, postorder + i, n - i - 1, (level + 1) % 2);
return preorder;
}
void level_order(struct TreeNode* T)
{
struct TreeNode* queue[Max];
int front = -1;
int rear = 0;
if (!T)return;
queue[rear] = T;
while (front != rear)
{
front++;
{
zigzag[top][0] = queue[front]->value;
zigzag[top][1] = queue[front]->flag;
top++;
}
if (queue[front]->left)
{
rear++;
queue[rear] = queue[front]->left;
}
if (queue[front]->right)
{
rear++;
queue[rear] = queue[front]->right;
}
}
return;
}
int main()
{
int n;
scanf("%d", &n);
{
for (int i = 0; i < n; i++)
{
scanf("%d", inorder + i);
}
for (int i = 0; i < n; i++)
{
scanf("%d", postorder + i);
}
}
struct TreeNode*T = transform(inorder, postorder, n, 0);
level_order(T);
for (int i = 0; i < n; i++)
{
if (zigzag[i][1])
{
if (i != 0)
printf(" ");
printf("%d", zigzag[i][0]);
}
else
{
int ti;
for (ti = i; zigzag[ti][1] == 0 && ti<n; ti++);
ti--;
for (int tti = ti; zigzag[tti][1] == 0 && tti >= i; tti--)
{
if (ti != 0)
printf(" ");
printf("%d", zigzag[tti][0]);
}
i = ti;
}
}
system("pause");
return 0;
}