public class LowestCommonAncestor {
private BTNode BTRoot;
private BTNode targetNode1, targetNode2;
public LowestCommonAncestor() {
BTRoot = new BTNode(1, null, null);
BTNode rootLeft = new BTNode(2, null, null);
BTRoot.left = rootLeft;
BTNode rootRight = new BTNode(3, null, null);
BTRoot.right = rootRight;
BTNode rootRightLeft = new BTNode(4, null, null);
BTNode rootRightRight = new BTNode(5, null, null);
rootRight.left = rootRightLeft;
rootRight.right = rootRightRight;
targetNode1 = rootRightLeft;
targetNode2 = rootLeft;
}
public static void main(String[] args) {
LowestCommonAncestor application = new LowestCommonAncestor();
System.out.println(application.findLCA().val);
}
private BTNode findLCA() {
return findLCAUtil(BTRoot, targetNode1, targetNode2);
}
private BTNode findLCAUtil(BTNode root, BTNode p, BTNode q) {
if (root == null) {
return null;
}
if (root == p || root == q) {
return root;
}
BTNode left = findLCAUtil(root.left, p, q);
BTNode right = findLCAUtil(root.right, p, q);
if (left != null && right != null) {
return root;
}
if (left == null && right == null) {
return null;
}
return left == null ? right : left;
}
private class BTNode {
int val;
BTNode left;
BTNode right;
public BTNode(int val, BTNode left, BTNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}