Search code examples
c++binary-treetraversal

Traversing a tree by name c++


I've been beating my head against the wall on this for a few hours. I have no idea what to do. I've restructured my function several times, and still haven't gotten it to work correctly.

This is for a programming assignment in my c++ class. It has to have a specific form, as in datatype, arguments, etc, as given by the instructor, so I can't change anything like that. We have to use character arrays, hence strcmp(). we have to return the person if we find it, or NULL if we don't.

Heres what i'm working with so far:

person *classname::getPersonByName(char *name, person *rt)
{
    if (rt != NULL)
    {
        if (strcmp(rt->Title, title) == 0)
        {
            return rt;
        }
        else
        {
            getPersonByName(title, rt->left);
            getPersonByName(title, rt->right);
            //return NULL;
        }
    }
}

In debug, it will find and return the person just fine by name. The problem is, is that it will promptly overwrite my return, and therefore not end up with the correct correct person.

the NULL at the bottom that is commented out ends up setting every call to NULL regardless of whether the search finds it or not.


Solution

  • the problem is, you are not returning anything from the recursive call.

    The idea is nothing difficult in fact, just translate this psuedo-code:

    // This is mostly a procedural way from your method signature, though you are using C++...
    Node getPersonByName(Node node, String name) {
        if (node is null) {
            return null
        }
    
        if (node.name == name) {
            return Node
        } 
    
        Node result = getPersonByName(node.left, name);
        if (result is not null) {  // found in node.left
            return result;
        }
    
        result = getPersonByName(node.right, name);
        if (result is not null) {  // found in node.right
            return result;
        }
    
        return null;
    }
    

    I will leave it as a homework for you to translate this to C/C++, and make the structure looks better by avoiding multiple points of return