Skip to content

Commit c14e72e

Browse files
committed
lowest common ancestor length pf path connecting two nodes
1 parent 215caf4 commit c14e72e

File tree

3 files changed

+16
-13
lines changed

3 files changed

+16
-13
lines changed

src/BinaryTree/BoundaryTraversalOfBinaryTree.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package BinaryTree;
1+
package BinaryTree;
22

33
/**
44
* Created by dheeraj on 6/28/2016.

src/BinaryTree/LowestCommonAncestor.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public static void main(String[] args) {
6060
root.right.right.right = new Node(15);
6161

6262
LowestCommonAncestor lowestCommonAncestor = new LowestCommonAncestor(root);
63-
System.out.println(lowestCommonAncestor.find(8, 15));
63+
System.out.println(lowestCommonAncestor.find(8, 5));
6464
}
6565

6666

src/BinaryTree/LowestCommonAncestorDistance.java

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,29 +26,32 @@ private void find(int one, int two) {
2626
findLca(root, one, two, 0);
2727
}
2828

29-
private static int dl = 0;
30-
private static int dr = 0;
31-
private static int droot = 0;
29+
private static int dl = -1;
30+
private static int dr = -1;
31+
private static int droot = -1;
3232

33-
private void findLca(Node root, int left, int right, int distance) {
33+
private int findLca(Node root, int left, int right, int distance) {
3434
if (root == null) {
35-
return;
35+
return -1;
3636
}
3737

3838
if (root.data == left || root.data == right) {
3939
if (root.data == left) {
40-
dl = distance;
40+
return distance;
4141
} else {
42-
dr = distance;
42+
return distance;
4343
}
4444
}
4545

46-
findLca(root.left, left, right, distance + 1);
47-
findLca(root.right, left, right, distance + 1);
46+
int l = findLca(root.left, left, right, distance + 1);
47+
int r = findLca(root.right, left, right, distance + 1);
4848

49-
if (dl > 0 && dr > 0) {
49+
if (l > -1 && r > -1 && droot == -1) {
50+
dl = l;
51+
dr = r;
5052
droot = distance;
5153
}
54+
return l > r ? l : r;
5255
}
5356

5457
public static void main(String[] args) {
@@ -66,7 +69,7 @@ public static void main(String[] args) {
6669
root.right.right.right = new Node(15);
6770

6871
LowestCommonAncestorDistance lowestCommonAncestor = new LowestCommonAncestorDistance(root);
69-
lowestCommonAncestor.find(15, 8);
72+
lowestCommonAncestor.find(7, 8);
7073
System.out.println((dl + dr - 2 * droot));
7174
}
7275

0 commit comments

Comments
 (0)