Reputation: 25
So I have this group project that's supposed to take in a text file, chop it up into species and sub species and that sort of thing. I've finished the chopping and the tree structure but I'm having a hard time getting my BuildGraph() to work. I've narrowed it down to the findNode() function that right now looks like
EDIT: comments, Also this is my first time posting so sorry if it's ugly. I had both of these changes in a different version but ended up getting rid of them somewhere?
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));
}
}
}
My Node structure looks like this...
public:
std::string data;
std::vector <Node*> children;
Node(std::string data){
this->data=data;
}
I'm pretty sure that the problem that I'm running into is something about the recursive call is going deeper rather than expanding somehow causing a segfault.
Can someone tell me if what I'm looking to do is possible?
Upvotes: 0
Views: 75
Reputation: 11968
You have 2 problems:
if(head->children[0]!=NULL){
You access children[0]
but you don't check if children is empty. I'm fairly sure this causes your SegFault.
return findNode(data, head->children.at(i));
You need to check if this is null before returning. In case it's null you want to check the other children.
Also pass const std::string& data
so that you don't copy the string at every call.
Upvotes: 1