-
Notifications
You must be signed in to change notification settings - Fork 3
/
Day-10
82 lines (55 loc) · 1.47 KB
/
Day-10
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
struct node{
int data ;
node* left ;
node* right ;
node(int x)
{
data = x ;
left = NULL ;
right = NULL ;
}
};
unordered_map<int,int> pretoin ;
vector<int> found_post ;
int pos = 0 ;
int maxreach ;
node* formtree(int pre[], int s , int e)
{
if(pos >= maxreach or s > e) return NULL ;
int val = pre[pos] ;
int x = pretoin[val] ; // x is position in inorder ;
pos++ ;
node* root = new node(val) ;
root->left = formtree(pre , s , x-1) ;
root->right = formtree(pre , x+1 , e) ;
}
void postorder_trav(node* root)
{
if(root == NULL) return ;
postorder_trav(root->left) ;
postorder_trav(root->right) ;
found_post.push_back(root->data) ;
}
class Solution{
public:
bool checktree(int pre[], int in[], int post[], int n)
{
for(int i = 0 ; i<n ; i++)
{
pretoin[in[i]] = i ;
}
pos = 0 ;
maxreach = n ;
node* root = formtree(pre , 0 , n-1 ) ;
found_post.clear() ;
postorder_trav(root) ;
if(found_post.size() != n) return 0 ;
//debc(post) ;
//debc(found_post) ;
for(int i = 0; i<n ; i++)
{
if(found_post[i] != post[i]) return 0 ;
}
return 1 ;
}
};