HighLife
HighLife

Reputation: 4344

Binary Tree Insertion Pointer Issue

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?

Upvotes: 0

Views: 375

Answers (2)

Filip Ros&#233;en
Filip Ros&#233;en

Reputation: 63797

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) {
   ...
}

Upvotes: 1

Pepe
Pepe

Reputation: 6480

You need to pass root by reference.

Upvotes: 1

Related Questions