Reputation: 54123
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
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
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
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