-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTREEORD.cpp
102 lines (81 loc) · 1.89 KB
/
TREEORD.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
#include <bits/stdc++.h>
using namespace std;
#define fast_cin() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
// #define OJ
#define LEFT 0
#define RIGHT 1
unordered_map<int, unordered_map<int, int>> tree;
int search(int data, int i, int j, vector<int> &arr)
{
while (i <= j)
{
if (arr[i] == data)
return i;
i++;
}
return -1;
}
int dfs(vector<int> &in, vector<int> &pre, int i, int j, int &index)
{
if (i > j)
return -2;
index++;
int root = search(pre[index], i, j, in);
if (root == -1)
return -1;
int left = dfs(in, pre, i, root - 1, index);
if (left == -1)
return -1;
int right = dfs(in, pre, root + 1, j, index);
if (right == -1)
return -1;
tree[root][LEFT] = left;
tree[root][RIGHT] = right;
return root;
}
bool checkPostorder(int root, vector<int> &in, vector<int> &post, int &index)
{
if (root == -2)
return true;
int left = tree[root][LEFT], right = tree[root][RIGHT];
checkPostorder(left, in, post, index);
checkPostorder(right, in, post, index);
return in[root] == post[index++];
}
void solve()
{
int n;
cin >> n;
vector<int> pre(n, -1), post(n, -1), in(n, -1);
for (int i = 0; i < n; i++)
cin >> pre[i];
for (int i = 0; i < n; i++)
cin >> post[i];
for (int i = 0; i < n; i++)
cin >> in[i];
int index = -1;
int root = dfs(in, pre, 0, n - 1, index);
index = 0;
if (root != -1)
{
if (checkPostorder(root, in, post, index) && index == post.size())
cout << "yes";
else
cout << "no";
}
else
cout << "no";
}
int main()
{
fast_cin();
#ifndef OJ
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
solve();
return 0;
}