-
Notifications
You must be signed in to change notification settings - Fork 0
/
Distance between two nodes
117 lines (98 loc) · 2.87 KB
/
Distance between two nodes
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
106
107
108
109
110
111
112
113
114
115
116
117
#include <map>
class Solution{
public:
/* Should return minimum distance between a and b
in a tree with given root*/
Node * findNode(Node * root , int target )
{
if(root == NULL)
{
return NULL;
}
if(root->data == target)
{
return root;
}
Node * a = findNode(root->right , target) ;
Node * b = findNode(root->left , target ) ;
if(a == NULL)
return b ;
else
return a ;
}
int findDistanceBetweenNodes(Node *root, int node1, int node2)
{
// Write your code here.
map < Node * , Node * > parent ;
queue < Node * > q ;
q.push(root) ;
while(!q.empty())
{
Node * f = q.front() ;
q.pop() ;
if(f->left != NULL)
{
q.push(f->left) ;
parent[f->left] = f ;
}
if(f->right != NULL)
{
q.push(f->right) ;
parent[f->right] = f ;
}
}
//finding target node
Node * a = findNode(root , node1) ;
if(a == NULL)
{
return -1 ;
}
Node * b = findNode(root , node2) ;
if(b == NULL)
return -1 ;
queue < Node * > qu ;
//finding nodes at distance k
qu.push(a) ;
int t = 0 ;
map <Node * , int> vis ;
vis[a] = 1;
while(!qu.empty())
{
int siz = qu.size() ;
for(int i = 0 ; i < siz ; i++)
{
Node* f = qu.front() ;
// cout << f->val << " " << siz << " " << t << endl ;
qu.pop() ;
if(f->data == node2)
{
return t ;
}
if(f->left != NULL && vis.count(f->left) == 0)
{
// cout << f->left->val << endl ;
qu.push(f->left) ;
vis[f->left] = 1 ;
}
if(f->right != NULL && vis.count(f->right) == 0)
{
// cout << f->right->val << " r" << endl ;
qu.push(f->right) ;
vis[f->right] = 1;
}
if (parent[f] != NULL && vis.count(parent[f]) == 0 && f != root) {
// cout << parent[f] << endl ;
// cout << parent[f] << "r" << endl ;
qu.push(parent[f]);
vis[parent[f]] = 1;
}
}
t = t + 1 ;
}
return t - 1 ;
}
int findDist(Node* root, int a, int b) {
// Your code here
return findDistanceBetweenNodes(root, a, b) ;
}
};