2011-03-27 214 views
0

我正在嘗試編寫一個函數,該功能將從四個樹中的一個節點返回到另一個節點的層數。查找從一個節點到另一個節點的層數

這裏是我到目前爲止,但我敢肯定,這是不正確的,我只是不能找出原因:

int levels(QtreeNode * orig, QtreeNode * n) { 

    //calculates the number of levels from orig to n 
    if(orig==n) 
     return 0; 
    if(!orig->isLeaf()) 
     return 1 + levels(orig->nwChild, n) + levels(orig->neChild, n) + levels(orig->swChild, n)+ levels(orig->seChild, n); 
    return 0; 

} 

任何想法?

+0

「從一個節點到另一個節點的級別數」 - 你的意思是深度差異或爲了到達另一個節點而必須經過的節點數量?例如,如果一個節點距根部X層深,另一個節點也是X層深度,結果應爲0?或者,如果兩者最深的共同祖先是根,那它應該是2X? – 2011-03-27 05:23:22

回答

1

你的錯誤是您在路徑末路的添加水平,但你需要計算的方式連接兩個節點

int levels(QtreeNode * orig, QtreeNode * n) 
{ 
    int path; 

    // found! 
    if (orig == n) 
     return 0; 
    // it's dead end, do not calc that way 
    if (orig->isLeaf()) 
     return -1; 
    path = levels(orig->nwChild, n); 
    // not dead end? it's fine, return that path 
    if (path >= 0) 
     return 1 + path; 
    path = levels(orig->neChild, n); 
    // not dead end? it's fine, return that path 
    if (path >= 0) 
     return 1 + path; 
    path = levels(orig->swChild, n); 
    // not dead end? it's fine, return that path 
    if (path >= 0) 
     return 1 + path; 
    path = levels(orig->seChild, n); 
    // not dead end? it's fine, return that path 
    if (path >= 0) 
     return 1 + path; 
    // there is no path between this nodes 
    return -2; 
} 
相關問題