首先,我並不陌生於C或C++。不過,我目前正在Mac Yosemite上使用C++。我只是試圖編寫一個遞歸函數來返回兩個節點的共同祖先,這些節點由其關鍵(數據)變量標識。邏輯很簡單,遍歷樹直到兩個節點都在同一個分支中,這些節點發散的節點是共同的祖先。有了這個想法,我想出了以下代碼:我的C++代碼有什麼問題?最少見的祖先
Node * commonAncestor(Node *n, int left_elem, int right_elem)
{
if (n == NULL || n->key()==left_elem || n->key() == right_elem){return NULL;}
if (left_elem < n->key() && right_elem > n->key()) {return n;}
if (left_elem > n->key() || right_elem < n->key()) {
cout<<"\n...Consider changing the order of the elements"<<endl;
}
if (left_elem < n->key() && right_elem < n->key()) {
commonAncestor(n->Left(), left_elem, right_elem);
}
if (left_elem > n->key() && right_elem > n->key()) {
commonAncestor(n->Right(), left_elem, right_elem);
}
}
我應該工作,我已經完成了類似的計劃。但是,該程序不能編譯。我得到編譯器錯誤"control may reach end of non-void function"
這很奇怪,因爲我有返回語句。另外,爲了避免這個錯誤,我嘗試在最後添加一個返回語句,它只返回根節點。我很困惑...我應該用XCode設置做些什麼嗎?我的邏輯錯了嗎?
難道把在return語句最後修復錯誤? – BWG 2015-01-21 02:47:57
是的,它讓我編譯但不會返回正確的節點。它返回t他根源......在這種情況下。 – 2015-01-21 03:41:20