Search code examples
c++xmltinyxml

recursive function with for loop: return value issue


This recursive xml traversal function that I'm trying to write does visit each node/element/tag correctly and it does pass the base case if statement during testing. What it doesn't do is maintain that correct return node after the function finishes unwrapping. My result is always NULL by the time the main program moves to the next line for some reason. I'm new to recursion so hopefully this is a simple error..

TiXmlNode* findNode(TiXmlNode* startNode, const char* searchWord){ 

    if (strcmp(startNode->Value(), searchWord) == 0){// base case
        return startNode;
    }
    else
    {
        for (TiXmlNode* node = startNode->FirstChild(); node; node = node->NextSibling())
        {
            findNode(node, searchWord);
        }
    }
}

Solution

  • Think about when the deepest findNode call returns startNode. Where does it go? Well it was called from here:

    findNode(node, searchWord);
    

    And what are you doing with that result? Nothing! You're ignoring it. You need to return it all the way down stack.

    Or think about it from the other side. The very first call to findNode, if it doesn't go inside the first if block, will never reach a return statement. It never gets a chance to return what you want.

    Here's how I'd write it:

    TiXmlNode* findNode(TiXmlNode* startNode, const char* searchWord){ 
    
        if (strcmp(startNode->Value(), searchWord) == 0){// base case
            return startNode;
        }
    
        for (TiXmlNode* node = startNode->FirstChild(); node; node = node->NextSibling())
        {
            TiXmlNode* foundNode = findNode(node, searchWord);
            if (foundNode != NULL) {
                return foundNode;
            }
        }
    
        return nullptr;
    }