jmasterx
jmasterx

Reputation: 54123

Recursive function that returns a bool?

I want to make a recursive function that iterates through a tree and the first time the condition hits, I want it to return. Would this be proper?

bool nodeExists(Node *root, Node *target)
{
    if(root == target)
    {
        return true;
    }

    for(int i = 0; i < root->nodes.size(); ++i)
    {            
        if(nodeExists(root->nodes[i],target)) {return true;}    
    }
    return false;
}

Upvotes: 1

Views: 10641

Answers (4)

oadams
oadams

Reputation: 3087

It's good, but I'd rather use a different identifier than "nodes". "children" is nice because it's clear and unambiguous.

Upvotes: 4

pegasus
pegasus

Reputation: 953

I think you wrote it properly. Did you test it?

Upvotes: 1

Evan Mulawski
Evan Mulawski

Reputation: 55334

That would work, since the return statement automatically exits the function. Another way would be:

bool nodeExists(Node *root, Node *target)
{
    if(root == target)
    {
        return true;
    }

    bool returnValue = false; 

    for(int i = 0; i < root->nodes.size(); ++i)
    {
        if(nodeExists(root->nodes[i],target)) {returnValue = true; break;}
    }
    return returnValue;
}

Upvotes: 0

Philip
Philip

Reputation: 3500

It looks good. Though you should really test your code, maybe you have any errors with pointers. (Depends on your Node class very much...)

Upvotes: 0

Related Questions