2013-03-06 134 views
3

我正在研究TreeDecomposition,樹中的每個節點可以有多個圖中的頂點。
現在,我試圖找到第一個節點其中包含頂點u從樹的根。在樹中遍歷

int Tree::traversing(Node* node, int u){ 
    //search in current node 
    int j = node->point_in_bag(u); //this function returns position of vertex u in node if not available -1 
    if(j != -1){ 
     return node->index; 
    } 
    else{  
    // traverse in its children 
    for(int k=0; k<node->children.size(); k++){ // children has the node's childs in it 
     Node* nod = node->children[k]; 
     cout << "nod index is " << nod->index << endl; 
     traversing(nod,u); // if vertex isn't found in node, traverse again in its children 
     } 
    } 
} 

我已經嘗試像上面那樣,但它沒有返回確切的節點索引。我在哪裏做錯了。

+0

你的縮排和評論是一團糟。實際上,一些顯然應該在註釋中的字符不是,從而導致代碼格式不正確。請努力爲其他人提供可讀代碼進行審閱。 – 2013-03-06 09:26:00

+0

對不起。我會盡力即興創作。 – user322 2013-03-06 09:35:44

+0

這個問題是算法中的一個基本問題。首先嚐試瞭解如何以遞歸或非遞歸方式遍歷二叉樹。 – user1929959 2013-03-06 09:38:10

回答

2

你忘了return這裏:

traversing(nod,u); 

所以你的遞歸調用返回了一些隨機數據(並已未定義行爲)。

即使您已經返回,您也只會返回第一個孩子的索引。
如果找不到,你需要繼續尋找。

for(int k=0; k<node->children.size(); k++){ 
    Node* nod = node->children[k]; 
    int childIndex = traversing(nod,u); 
    if (childIndex != -1) 
     return childIndex; 
} 
return -1; 

您應該增加編譯器的警告級別。

+0

哦,耶..謝謝你的時間花花公子。現在它是固定的。乾杯。 – user322 2013-03-06 09:34:15

+0

@ user2139106在您的編譯器中啓用警告。它應該能夠捕捉函數不返回任何內容的情況。或者,如果它們已啓用,請不要忽略它們。 – 2013-03-06 09:39:00

+1

沒辦法修復它,現在你只能遍歷第一個孩子。 – 2013-03-06 09:43:00