-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMin_dist_btw_2given_nodes_in_BT.cpp
64 lines (58 loc) · 1.36 KB
/
Min_dist_btw_2given_nodes_in_BT.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
/* A binary tree node
struct Node
{
int data;
Node* left, * right;
}; */
class Solution{
public:
/* Should return minimum distance between a and b
in a tree with given root*/
Node * LCA(Node* root, int a, int b)
{
if(root==NULL || root->data == a|| root->data == b)
{
return root;
}
Node* left = LCA(root->left,a,b);
Node* right = LCA(root->right,a,b);
if(! left)
{
return right;
}
else if(!right)
{
return left;
}
else{
return root;
}
}
int findDistUtil(Node* root, int k) {
if(root == NULL)
{
return -1;
}
if(root->data == k)
{
return 0;
}
int left = findDistUtil(root->left,k);
if(left>=0)
{
return 1+left;
}
int right = findDistUtil(root->right,k);
if(right>=0){
return 1+right;
}
return -1;
}
int findDist(Node* root, int a, int b) {
// Your code here
Node * common = LCA(root,a,b);
int distA = findDistUtil(common,a);
int distB = findDistUtil(common,b);
return (distA+distB);
}
};