我有这个代码,它计算给定的Least common Ancestor
两个nodes
。Binary tree
目前,它假设两个节点都存在。我可以编写一个辅助方法来检查节点是否存在,然后调用该LCABT
方法。那将需要遍历树两次。我想知道是否有一种方法可以检查和处理当前代码中不存在节点的情况。
//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;
}