0

I have two functions in a class that creates a binary tree:

void Btree::insertNode(node* r, node* newNode){
    if (r == NULL)
        r = newNode;
    else if (greater(root, newNode))
        insertNode(r->left, newNode);
    else
        insertNode(r->right, newNode);
}

void Btree::load(){
    for (int i = 0; i < mainVec.size(); ++i){
        node* n = new node;
        n->index = i;
        for (int j = 0; j < mainVec[i].size(); ++j)
            n->s += mainVec[i][j];
        insertNode(root, n);
    }
    printTree(root);
    return;
}

I'd like load to fill up the tree at root (root is a private node pointer node* root), but every time insertNode exits root is still a null pointer. Could someone point out my stupid mistake?

2 Answers 2

1

You'll need to make parameter r passed as a reference to be able to change root from inside the function insertNode.

See the below:

void Btree::insertNode(node*& r, node* newNode) {
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to pass root by reference.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.