简体   繁体   中英

C++ - Return in Recursion of Tree

class Person {
private:
    char* name;
    int numChildren;
    Person** childrenList;
public:
    Person(char* name);
    ~Person();
    // member functions
        // ...
};

Suppose I create a Person by this code: Person* me = new Person("Alex"); , Alex 's descendants' object will also be created. For a specific instance, the structure will be like this: 在此处输入图片说明

I'd like to implement a function const Person* Person::findPerson(const Person* thisPerson, const char* target_name) const; , that searches through all Person to find the one with name equals target_name .
Here is my code:

const Person* Person::findPerson(const Person* thisPerson, const char* target_name) const {
    if (strcmp(thisPerson->name(), target_name) == 0)
        return thisPerson;
    for (int i = 0; i < thisPerson->numChildren(); i++)
        findPerson(thisPerson->childrenList[i], target_name);
}

I think the code will work but the compiler thinks it might returns nothing and don't let me compile it. And also, I don't know how to return nullptr if nobody is found.

You need to:

  1. return the result of the recursive call, if successful
  2. return nullptr if the person is not found
const Person* Person::findPerson(const Person* thisPerson, const char* target_name) const {
    if (strcmp(thisPerson->name(), target_name) == 0)
        return thisPerson;
    for (int i = 0; i < thisPerson->numChildren(); i++) {
        const Person *p = findPerson(thisPerson->childrenList[i], target_name);
        // Found in child tree? Return it (terminate recursion)
        if (p) return p;
    }
    // Not found in this branch of the tree
    return nullptr;
}

Although it seems a bit odd to pass a Person pointer to a Person member function. Also, numChildren and name are member variables, not functions.

Shouldn't it be:

const Person* Person::findPerson(const char* target_name) const {
    if (strcmp(name, target_name) == 0)
        return this;
    for (int i = 0; i < numChildren; i++) {
        const Person *p = childrenList[i]->findPerson(target_name);
        // Found in child tree? Return it (terminate recursion)
        if (p) return p;
    }
    // Not found in this branch of the tree
    return nullptr;
}

And, I am obliged to ask why you are not using std::vector and std::string instead of arrays and char pointers?

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