2016-04-15 70 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,这样你就不会在每次调用时复制字符串。

相关问题