-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLowestCommonAncestor.java
27 lines (22 loc) · 1001 Bytes
/
LowestCommonAncestor.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
package com.anudev.ds.trees;
public class LowestCommonAncestor {
public static Node findLowestCommonAncestor(Node rootNode, Node firstNode, Node secondNode) {
if (rootNode == null) {
return null;
}
if (rootNode.getValue() == firstNode.getValue()
|| rootNode.getValue() == secondNode.getValue()) {
return rootNode;
}
Node leftNodeFound = findLowestCommonAncestor(rootNode.getLeftNode(), firstNode, secondNode);
Node rightNodeFound = findLowestCommonAncestor(rootNode.getRightNode(), firstNode, secondNode);
if (leftNodeFound != null && rightNodeFound != null) {
System.out.println("Lowest common Ancestor of "
+ firstNode.getValue() + " and "
+ secondNode.getValue() + " is " + rootNode.getValue());
} else if (leftNodeFound != null) {
return leftNodeFound;
} else return rightNodeFound;
return null;
}
}