Search code examples
c++classrecursionbinary-search-treefunction-definition

How do I get rid of the warning in this simple recursive implementation of BST


I am trying to implement DSs in C++, here is a simple implementation of a Binary Search Tree Class with insert and search functions. The code compiles and gives the output as required.
Someone at codereview pointed out that the search function gives a warning and the code in the search function is broken. The warning is similar to 'not all control paths have a return statement' but I thought that is how a recursive function would look like. Is the warning a problem and how do I get rid of it? Also, how is the code broken? Thank you.

#include <stdio.h>
#include <iostream>

class BstNode{
int data;
BstNode* left;
BstNode* right;

public:
BstNode(int data)
{
    this->data = data;
    this->left = NULL;
    this->right = NULL;
}
~BstNode();

void Insert(int data)
{
    if(this->data >= data)
    {
        if (this->left == NULL)
            this->left = new BstNode(data);
        else 
            this->left->Insert(data);
    }
    else
    {
        if (this->right == NULL)
            this->right = new BstNode(data);
        else 
            this->right->Insert(data);
    }
}

bool Search(int data)
{
    if(this->data == data)
        return true;
    else if(this->data >= data)
    {
        if(this->left == NULL)
            return false;
        else
            this->left->Search(data);
    }
    else
    {
        if(this->right == NULL)
            return false;
        else
            this->right->Search(data);
    }

}
};

int main()
{
BstNode* ptr_root = new BstNode(15);
ptr_root->Insert(10);
ptr_root->Insert(16);
int num;
std::cout<<"Enter the number: \n";
std::cin>> num;
if (ptr_root->Search(num))
    std::cout<<"Found\n";
else
    std::cout<<"Not Found\n";

return 0;
}

Solution

  • This function Search returns nothing in these paths

        else
            this->left->Search(data);
    

    and

        else
            this->right->Search(data);
    

    You have to write

        else
            return this->left->Search(data);
    

    and

        else
            return this->right->Search(data);
    

    The function can be defined with a single return statement the following way

    bool Search( int data ) const
    {
        return ( this->data == data ) || 
               ( this->data >= data ? this->left  && this->left->Search( data )
                                    : this->right && this->right->Search( data ) );    
    }
    

    Actually the condition

    this->data >= data
    

    may be substituted for

    this->data > data