c++recursionsearchtreerapidxml

What is wrong with this recursive function for searching a word match inside a non binary tree?


I have this snippet of code inside my project that has to search for an exact match inside an XML tree parsed with RapidXML. It does find the match but at the end it's always a null pointer match. I can't figure out the order in which I should code the function can somebody help me out?

xml_node<>* processNode(xml_node<>* node, char* lookout)
    {
        for (xml_node<>* child = node->first_node(); child; child = child->next_sibling())
        {
            cout << "processNode: child name is " << child->name() << " comparing it with " << lookout << endl;
            if (strcmp(child->name(), lookout) == 0) {
                return child;
            }
            processNode(child, lookout);
        }
    
        return nullptr;
    }

Solution

  • You need to return the result of the recursion – recursive functions work exactly like non-recursive function and return to the place where they were called.

    However, you can't return it directly, because then you would only ever look in one of the children.
    You need to first store the value, and then return it only if you found what you were looking for.
    Something like this:

        for (xml_node<>* child = node->first_node(); child; child = child->next_sibling())
        {
            if (strcmp(child->name(), lookout) == 0) {
                return child;
            }
            xml_node<>* result = processNode(child, lookout);
            if (result != nullptr) {
                return result;
            }
        }