2016-04-15 66 views
-1

所以我有這個應該在文本文件中的組項目,把它分成物種和亞物種等等。我完成了砍和樹結構,但我很難讓BuildGraph()工作。我已經縮小到findNode()函數,現在看起來像在任意數量的子節點樹中找到一個節點

編輯:評論,這也是我第一次發佈非常抱歉,如果它是醜陋的。 我在一個不同的版本有這兩個變化,但最終擺脫他們的地方?

Node* findNode(std::string data, Node* head){ 
if (head == NULL){ 
    return NULL; 
} 
else if(head->data == data){ 
    return head; 
} else { 
    if(head->children[0]!=NULL){ 
     for(int i = 0; i<head->children.size();i++){ 
      return findNode(data, head->children.at(i)); 
     } 
    } 
} 

我的節點結構看起來像這樣...

public: 
    std::string data; 
    std::vector <Node*> children; 

    Node(std::string data){ 
     this->data=data; 
    } 

我敢肯定,我正在運行到的問題是一些有關的遞歸調用不斷深入,而不是莫名其妙地擴大導致段錯誤。

有人可以告訴我,我想要做什麼是可能的嗎?

+1

'return findNode(data,head-> children.at(i));',你錯過了'return' –

+0

爲什麼不檢查'head'是否爲空? –

回答

1

你有2個問題:

if(head->children[0]!=NULL){ 

您訪問children[0],但你不檢查,如果孩子是空的。我相當確定這會導致您的SegFault。

return findNode(data, head->children.at(i)); 

您需要檢查返回前是否爲空。如果它爲空,你想檢查其他孩子。

同時通過const std::string& data,這樣你就不會在每次調用時複製字符串。

相關問題