MAHA JAVED
MAHA JAVED

Reputation: 13

Function does not stop executing after return statement

I am working in C++ and have written a function but it does not stop the execution after the return statement.

BSTNode* search(BSTNode* root, int data)
{
    BSTNode* newroot=root;
    int count = 1;
    if (root->data == data)
    {
        newroot=root;
        count = 0;
    }
    else
    {
        search(root->left, data);
        if (count != 0)
            search(root->right, data);
    }
    return newroot;
}

How can I make it stop executing after returning the value?

Upvotes: 0

Views: 1169

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596703

Your count variable is useless and should be removed. The recursive calls to search() do not update it, so if (count != 0) is always evaluated as true.

You are also ignoring the return value of the recursive search() calls to stop the search once a matching node is found.

And you are ignoring the possibility of null pointers being present in the tree.

Try something more like this instead:

BSTNode* search(BSTNode* root, int data)
{
    if (!root)
        return nullptr;

    if (root->data == data)
        return root;

    BSTNode *node = search(root->left, data);
    if (!node)
        node = search(root->right, data);

    return node;
}

Upvotes: 5

Related Questions