mercredi 16 août 2017

BST not adding elements

So I wrote this code to add elements to a Binary Tree->

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 ?

Aucun commentaire:

Enregistrer un commentaire