-
Notifications
You must be signed in to change notification settings - Fork 0
/
Number Of Turns - Binary Tree GFG Practice
85 lines (82 loc) · 1.53 KB
/
Number Of Turns - Binary Tree GFG Practice
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
Node* lca(Node *root,int f,int s)
{
if(root==NULL)
return NULL;
if(root->data == f)
return root;
if(root->data == s)
return root;
Node* l=lca(root->left,f,s);
Node* r=lca(root->right,f,s);
if(l && r)
return root;
if(l==NULL)
return r;
else
return l;
}
void solve(Node *root,unordered_map<Node*,Node*> &m)
{
if(root==NULL)
return ;
if(root->left)
{
m[root->left]=root;
solve(root->left,m);
}
if(root->right)
{
m[root->right]=root;
solve(root->right,m);
}
}
int NumberOFTurns(struct Node* root, int first, int second)
{
// Your code goes here
Node* c=lca(root,first,second);
Node* ff=lca(root,first,first);
Node* ss=lca(root,second,second);
unordered_map<Node*,Node*>mp;
solve(root,mp);
vector<int>a,b;
while(ff!=c)
{
Node* tmp=mp[ff];
if(tmp->left==ff)
{
a.push_back(0);
}
else
{
a.push_back(1);
}
ff=tmp;
}
while(ss!=c)
{
Node* tmp=mp[ss];
if(tmp->left==ss)
{
b.push_back(0);
}
else
{
b.push_back(1);
}
ss=tmp;
}
int count=0;
for(int i=1;i<a.size();i++)
{
if(a[i]!=a[i-1])
count++;
}
for(int i=1;i<b.size();i++)
{
if(b[i]!=b[i-1])
count++;
}
if(a.size() >0 && b.size() > 0)
count++;
return count;
}