-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPOJ-TREEORD.cpp
More file actions
90 lines (63 loc) · 1.34 KB
/
SPOJ-TREEORD.cpp
File metadata and controls
90 lines (63 loc) · 1.34 KB
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
#include <bits/stdc++.h>
using namespace std;
typedef struct node{
int value;
struct node *left;
struct node *right;
}node;
node* createNode(int value){
node *temp = new node;
temp->value = value;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int search(int vet[], int start, int end, int value){
for (int i = start; i <= end; i++){
if(vet[i] == value)
return i;
}
}
int j = 0;
node* construct(int in[], int pre[], int start, int end){
if(start > end)
return NULL;
node *temp = createNode(pre[j++]);
if (start == end)
return temp;
int k = search(in, start, end, temp->value);
temp->left = construct(in, pre, start, k-1);
temp->right = construct(in, pre, k+1, end);
return temp;
}
int checkPost(node* node, int post[], int k){
if (node == NULL)
return k;
k = checkPost(node->left, post, k);
k = checkPost(node->right, post, k);
if (node->value == post[k])
k++;
else
return -1;
return k;
}
int main(){
int in[8000];
int pre[8000];
int post[8000];
int n;
cin >> n;
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];
}
node *root = construct(in, pre, 0, n - 1);
int k = checkPost(root, post, 0);
(k == n) ? cout << "yes" : cout << "no";
return 0;
}