I have this code to find the least common Ancestor
of two nodes
in binary tree
. I think the time complexity is O(log n)
. but expert opinions are needed. This code works fairly well on my inputs, but I am not sure if I have tested it exhaustively.
here is the 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 return right;
}
I'm pretty sure this runs in
O (n)
because you are passing through the whole graph (i.e. at each node you are going in both directions - right and left).I would suggest reading Tarjan's off-line lowest common ancestors algorithm.