Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading