Algorithm 查找最低共同祖先代码解释
我正在查看以下来自编程访谈的代码,但我似乎无法理解它到底是如何工作的。这个方法不总是返回null吗Algorithm 查找最低共同祖先代码解释,algorithm,Algorithm,我正在查看以下来自编程访谈的代码,但我似乎无法理解它到底是如何工作的。这个方法不总是返回null吗 // Overload it to handle nodes as well Node findLowestCommonAncestor( Node root, Node child1, Node child2 ){ if( root == null || child1 == null || child2 == null ){
// Overload it to handle nodes as well
Node findLowestCommonAncestor( Node root, Node child1,
Node child2 ){
if( root == null || child1 == null || child2 == null ){
return null;
}
return findLowestCommonAncestor( root, child1.getValue(),
child2.getValue() );
}
从代码片段中,我们不知道getValue返回什么。因此,如果存在其他重载版本的FindLowestCommonSenator,并且getValue返回的不是Node,那么代码段中对FindLowestCommonSenator的调用不会递归地调用自身。如果这是确切的代码,那么它将返回
null
或者在执行getValue()时引发异常
在其中一个子节点上。is不会做的是FindLowestCommonSenator
。@Oded或由于无限递归而导致的堆栈溢出。@Jan-不太可能,除非树非常深(如果它那么深,应用程序可能会事先遇到内存不足的问题)。@Oded谁说它是一棵树?您只知道节点::getValue()
返回一个节点
。我们知道getValue返回节点吗?FindLowestCommon祖先是否还有其他方法签名(重载),或者这段代码是已知的全部吗?