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

5.1k views Asked by At

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;
}
3

There are 3 answers

0
Aumnayan On BEST ANSWER
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;
}
0
Michał Trybus On

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;
2
Mr.C64 On
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.