-
Notifications
You must be signed in to change notification settings - Fork 2
/
MinDistanceBT.java
82 lines (65 loc) · 1.49 KB
/
MinDistanceBT.java
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
// Min distance between two given nodes of a Binary Tree
/* A Binary Tree node
class Node
{
int data;
Node left, right;
Node(int item) {
data = item;
left = right = null;
}
} */
/* Should return minimum distance between a and b
in a tree with given root*/
class GfG {
int findDist(Node root, int a, int b) {
// Your code here
Node LCA = lca(root,a,b);
return findLevel(LCA,a) + findLevel(LCA,b);
}
Node lca(Node root, int n1,int n2)
{
if(root == null){
return null;
}
if(root.data == n1 || root.data == n2){
return root;
}
Node left = lca(root.left,n1,n2);
Node right = lca(root.right,n1,n2);
if(left != null && right != null){
return root;
}
if(left == null && right != null){
return right;
}
else{
return left;
}
}
int findLevel(Node root,int x){
if(root == null){
return -1;
}
Queue<Node> Q = new LinkedList<>();
Q.add(root);
int lvl = 0;
while(! Q.isEmpty()){
int len = Q.size();
for(int i = 0; i < len; i++){
Node cur = Q.poll();
if(cur.data == x){
return lvl;
}
if(cur.left != null){
Q.add(cur.left);
}
if(cur.right != null){
Q.add(cur.right);
}
}
lvl += 1;
}
return -1;
}
}