krrishna
krrishna

Reputation: 2088

Implementing BinarySearchTree using Single Linked List

I have the below code which I am using to implement BinarySearchTree. Somehow it doesn't build the binarytree.Can anybody help what is the issue ?

typedef struct BinarySearchTree

{

    struct BinarySearchTree *left;
    int nodeval;
    struct BinarySearchTree *right;

} 
BST;

BST *root=NULL;

void addrootnode(BST *,int );

void addnode(BST *,int );

void deletenode(int );

void printnodes();

main()

{

    int nodeval;
    char choice;
    printf("\n r->rootnode \n a->add \n d->delete \n p->print \n e->exit\n");
    while (1)
    {   
        printf("\nEnter your choice:");
        scanf("%c",&choice);
        switch (choice)
        {
        case 'r':
            printf("\nEnter the root node value to add: ");
            scanf("%d",&nodeval);
            addrootnode(root,nodeval);
            break;
        case 'a':
            printf("\nEnter the node value to add: ");
            scanf("%d",&nodeval);
            addnode(root,nodeval);
            break;
        case 'd':
            printf("\nEnter the node value to delete: ");
            scanf("%d",&nodeval);
            break;
        case 'p':
            //printf("\n");
            printnodes(root);
            break;
        case 'e':           
            exit(0);
        default:
            break;
        }
    }
    getchar();

}//end of main

//addrootnode

void addrootnode(BST *ptr,int num)

{

    if(ptr==NULL)
    {
        ptr=(BST *) malloc(sizeof(BST));
        ptr->left=NULL;
        ptr->nodeval=num;   
        ptr->right=NULL;        
        root=ptr;       
    }
}
//add node

void addnode(BST *ptr,int num)
{

    if(ptr==NULL)
    {
        ptr=(BST *) malloc(sizeof(BST));
        ptr->left=NULL;
        ptr->nodeval=num;   
        ptr->right=NULL;        


    }
    else if(num < ptr->nodeval )
    {       
        addnode(ptr->left,num);
    }
    else
    {

        addnode(ptr->right,num);
    }

}

//delete functionality

void deletenode(int nodeval)
{
}

//print all nodes

void printnodes(BST *ptr)

{

    if (ptr)

    {
        printnodes(ptr->left);
        printf("%d\t",ptr->nodeval);
        printnodes(ptr->right);
    }

}

Upvotes: 0

Views: 2999

Answers (1)

CubeSchrauber
CubeSchrauber

Reputation: 1199

You should not use BST *ptr as argument to addnode. You try to assign a value to it but at this time ptr is a local variable to the function addnode an does not alter the intended left or right pointer of the parent node.

Try to think about using BST **ptr instead.

Upvotes: 1

Related Questions