Shubham Anand
Shubham Anand

Reputation: 128

BST not adding elements

So I wrote this code to add elements to a Binary Tree.As shown in the following figure.

typedef struct node{
    int key;
    node *right;
    node *left;
}*nodePtr;

nodePtr root = NULL // As global variable.

void addElement(int key, nodePtr tempRoot){
    if(tempRoot!=NULL){
        if(tempRoot->key > key){
            if(tempRoot->left!=NULL)
                addElement(key, tempRoot->left);
            else
                tempRoot->left = createLeaf(key);
        }
        else if(tempRoot->key < key){
            if(tempRoot->right!=NULL)
                addElement(key, tempRoot->right);
            else
                tempRoot->right = createLeaf(key);
        }
    }else if(tempRoot==NULL)
        tempRoot = createLeaf(key);
}

int main(){
    int arr[] = {50,45,23,10,8,1,2,54,6,7,76,78,90,100,52,87,67,69,80,90};

    for(int i=0; i<20; i++){
        addElement(arr[i], root);
    }

    return 0;
}

The issue is this code doesnt add anything to the tree when I try to print the tree. However if I replace the last part of the code by this code instead;

    else if(root==NULL)
        root = createLeaf(key);

Why is this happening ?

Upvotes: 0

Views: 50

Answers (1)

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

You receive tempRoot by value, so changing it inside the function will not be reflected outside.And when you directly access the global root, you can indeed change its value inside the function.

void addElement(int key, nodePtr tempRoot){

You can use references here.

void addElement(int key, nodePtr &tempRoot)

Upvotes: 5

Related Questions