Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ binary search tree using recursion, return node problem

I am trying to create a function that receives a node and a value to enter into the tree. I am passing values as (Node* node, int value). But when I return that node the error message appears as "No suitable constructor exists to convert from "Node" to "Node". I have seen a few questions much similar to my problem but I was unable to understand the answers provided. I am new to the tree Data structure concept, So please try to explain it simply.

class Node {
    public:
        int data;
        Node* left;
        Node* right;
        Node(int value)
        {
            data = value;
            left = right = nullptr;
        }
    };
    Node* root = nullptr;
    
    Node insert(Node *node, int value)
    {
        if (node == nullptr)
        {
            node = new Node(value);
            return node;
       }
    
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are trying to return a pointer to Node but the signature of the method says you want to return a Node value. Change the return signature to a pointer of Node

Node* insert(Node *node, int value)
{
    if (node == nullptr)
    {
        node = new Node(value);
        return node;
    }
    // also problem here if node is a nullptr, how to handle this
    // you could throw exception or return nullptr
    return nullptr;

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading