1

I want a method that creates a binary tree from an array and returns nothing. So I would have to work by reference but I am having some troubles with the proper syntax to use.

I have obviously tried to search before posting this question, I have seen similar posts but no answer were truly helpfull.

Here what i have done so far :

My Class :

class Node
{
private:
    int data;
    Node* left;
    Node* right;
public:

    [...]

    void make_tree(Node* node, int values[], int size);
};

The method :

// Every operations are done a copy of node, I want them to be done on the original object
void Node::make_tree(Node* node, int values[], int size)
{
    if (size <= 0)
    {
        return;
    }
    else
    {

        if (!node)
        {
            node = new Node(values[size]);
        }
        else if (!node->has_data())
        {
            node->set_data(values[size]);
        }
        // recursive call
        make_tree(node->left, values, size - 1);
        make_tree(node->right, values, size - 1);

    }
}

The call :

int main()
{
    int tab[] = { 5,3,4,9,7,6 };
    Node* root = new Node();

    /* I want "root" to be passed by reference so every modifications
     are done on the original object and not a copy who will be destroyed
     at the end of the method scope. */

    root->make_tree(root, tab, 6);

    root->print_tree();   // there is nothing more in root
}

Since I am already passing a pointer to the object "root", I am confused on how I could do it.

Thank you.

PS: I am aware that my recursive call does not do what I described it should do. That is a problem for an other time.

PPS : first post btw, so if you see something I did wrong, please, tell me.

Noircis
  • 46
  • 4

1 Answers1

2
void Node::make_tree(Node* node, int values[], int size);

Node pointer cannot be modified inside the function, as you pass it by value (only the copy is modified).

You can use a reference, as suggested in comments :

 void Node::make_tree(Node* &node, int values[], int size);

Or you can also use a pointer to a pointer void Node::make_tree(Node** node, int values[], int size); but there will be more work to modify your code.

Fryz
  • 2,119
  • 2
  • 25
  • 45