简体   繁体   中英

Finding a Node in a tree of Nodes with an arbitrary number of children

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM