开发者

Recursive function that returns a bool?

开发者 https://www.devze.com 2023-01-24 06:13 出处:网络
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?

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

精彩评论

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

关注公众号