2012-12-26 33 views
0

我正在看編程訪談暴露以下代碼,我似乎無法理解它的工作原理。這個方法不會總是返回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()); 
} 
+2

如果這是確切的代碼,那麼它會在其中一個子節點上執行'getValue()'時返回null或拋出異常。不會做的是'findLowestCommonAncestor' ... – Oded

+0

@Oded或堆棧溢出由於無限遞歸。 –

+0

@Jan - 不太可能,除非樹非常深(如果深度很深,應用程序會事先觸發內存不足)。 – Oded

回答

2

從代碼片段中,我們並不真正知道getValue返回的內容。因此,如果有其他重載版本的findLowestCommonAncestor,並且getValue返回的是Node以外的內容,那麼在代碼片段中調用findLowestCommonAncestor不會遞歸地調用它自己。