开发者

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)
{开发者_如何学Go
    if(root == target)
    {
        return true;
    }

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


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


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


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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜