I have this code, which calculates Least common Ancestor of given two nodes in a Binary tree.
Currently, it assumes both nodes are present. I can write a helper method just to check if the nodes are present and then call the LCABT method. That would require traversing the tree twice. I am wondering if there is a way to check and handle a situation when node is not present with my current code.
//LCA of Binary tree
public static Node LCABT(Node root, int v1, int v2){
if (root==null)
return null;
if (root.data==v1 || root.data==v2){
return root;
}
Node left = LCABT(root.left,v1,v2);
Node right = LCABT(root.right,v1,v2);
if(left!=null && right!=null)
return root;
else if (left!=null)
return left;
else if (right!=null)
return right;
return null;
}
Make the function return a pair
(state, lca).statemust be one of:The function should begin by checking for base cases:
Otherwise, recurse on its left and right children, to see if one of them solves the problem all by itself:
and if either
s1ors2is 3, then the LCA has already been found (it's eitherlca1orlca2, respectively) and can be returned immediately. (In fact, you can even obtain a speedup by checking whethers1 == 3before making the second call toLCABT(): if it is, then we already have the LCA and don't need the second call.)Otherwise, set
s = s1 | s2(i.e. bitwise OR). Ifs == 3then we know thatrootis the LCA, but we haven't yet considered all ways in which it can be the LCA: it can still be the LCA when only one ofv1andv2is present at or under its children, provided that the other value is atrootitself:Now all cases in which
rootis the LCA implys == 3, so ifs == 3then we can return(3, root)immediately:Otherwise, at most one of
v1andv2is at or underroot, so we should return a value indicating which one it is:Finally, the original top-level call to
LCABT()should obviously regard the function as succeeding only when it returns astatevalue of 3.Another advantage of this algorithm over yours is that it will not be fooled by duplicate copies of either
v1orv2in the tree.