mr nooby noob
mr nooby noob

Reputation: 2253

Tree implementation in C++: Cannot convert Node to Node*

My error is regarding the last two assignment statements in main. I am trying to create a basic tree by having each node point to 2 other nodes: left and right. I have also tried adding * in front of n1, n2, and n3 when creating them, but that did not work either...

#include <iostream>
#include <string.h>

using namespace std;

class Node{

    public:
    string value;
    Node *left, *right;

    public:
    Node(string s, Node *l, Node *r){
        value = s;
        left = l;
        right = r;
    }
    void display(){
        cout << value << left->value << right->value;
    }

};
int main(){

    Node n1("this", NULL,NULL);
    Node n2("is", NULL, NULL);
    Node n3("next", NULL, NULL);
    n1.left = n2;
    n1.right = n3;

    n1.display();
    return 0;
}

Upvotes: 1

Views: 5134

Answers (3)

Mr.C64
Mr.C64

Reputation: 42924

Node n1("this", NULL,NULL);
Node n2("is", NULL, NULL);
Node n3("next", NULL, NULL);

n1.left = n2;
n1.right = n3;

left and right are pointers to Node instances (in fact, you defined them as Node *left, Node *right).

So you have to take the address of n2 and n3 to do the assignments:

n1.left = &n2;
n1.right = &n3;

Moreover, note that in C++11/14, you should use nullptr instead of NULL.

Upvotes: 1

Michał Trybus
Michał Trybus

Reputation: 11784

When you create nodes like:

Node n1("this", NULL,NULL);

you create them on stack, so n1 is an object. n1.left is a pointer, so you have to assign a pointer to it too. In order to get a pointer to an object, you have to use the &operator, like:

n1.left = &n2;

Upvotes: 1

Aumnayan
Aumnayan

Reputation: 669

int main(){

    Node n1("this", NULL,NULL);
    Node n2("is", NULL, NULL);
    Node n3("next", NULL, NULL);
    n1.left = &n2;
    n1.right = &n3;

    n1.display();
        return 0;
}

Upvotes: 5

Related Questions