In graph theory and computer science, the lowest common ancestor (LCA) of two nodes v and w in a tree or directed acyclic graph (DAG) is the lowest (i.e. deepest) node that has both v and w as descendants, where we define each node to be a descendant of itself (so if v has a direct connection from w, w is the lowest common ancestor).
in this tree, the lowest common ancestor of the nodesx and y is marked in dark green. Other common ancestors are shown in light green.
Problem 1. Find the LCA of two given nodes in Binary Search Tree.
The edge case here is, when root.data = l.data && root.data < r.data, root is the LCA of the two nodes.
public static TreeNode findLCA(TreeNode root, TreeNode a, TreeNode b) {
if(root==null || a== null || b==null) return root;
TreeNode l = a.data<b.data ? a:b;
TreeNode r = a.data>b.data ? a:b;
if(root.data>=l.data && root.data<=r.data) return root;
else if(root.data < l.data) return findLCA(root.right,l,r);
else return findLCA(root.left,l,r);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.right = new TreeNode(11);
root.left = new TreeNode(9);
root.left.left = new TreeNode(6);
root.left.left.left = new TreeNode(3);
root.left.left.right = new TreeNode(8);
root.left.left.right.left = new TreeNode(7);
TreeNode a = new TreeNode(3);
TreeNode b = new TreeNode(7);
System.out.print(findLCA(root,a,b).data);
<span style="white-space:pre"> </span>// 6
}
Problem 2. Find the LCA of two given nodes in Binary Tree.
public static TreeNode findLCA(TreeNode root, TreeNode a, TreeNode b){
// if either a or b is the root then root is LCA.
if(root==null || root.data == a.data || root.data == b.data) return root;
else{
//find the LCA from root's left subtree
TreeNode l = findLCA(root.left,a,b);
TreeNode r = findLCA(root.right,a,b);
// if one of a or b is in leftsubtree and other is in right
// then root is the LCA.
if(l!=null && r!=null)
return root;
// else if l is not null, l is LCA.
else if(l!=null)
return l;
else
return r;
}
}