我有这段代码可以least common Ancestor
在nodes
. binary tree
我认为时间复杂度是O(log n)
. 但需要专家意见。这段代码在我的输入上运行得相当好,但我不确定我是否已经对它进行了详尽的测试。
这是代码
//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;
}