Binary search tree insertion - root always null

人走茶凉 提交于 2019-12-02 02:12:23

问题


I have ds code for inserting values in a binary search tree using recursion. The problem is that the root always remains null. Upon execution, the 1st printf() prints 10 but the 2nd printf (after insertRec(10)) does not print anything as root is null.

#include<stdio.h>
#include<malloc.h>

struct llist
{
       int data;           
      struct llist *left;
      struct llist *right;       
};
typedef struct llist node;

void insertRec(node *r, int num)
{   
     if(r==NULL)
     {      
             r=(node*)malloc(sizeof(node)); 
             r->data=num; 
             r->left=NULL; 
             r->right=NULL; printf("%d ",r->data); //1st printf

     }     
     else
     {
         if(num < r->data)
           insertRec(r->left, num);             
         else
           insertRec(r->right, num);                 
     }         
}    
void display(node *x)
{          
     if(x != NULL)
     {
       display(x->left);
       printf("%d-->",x->data);
       display(x->right);        
     }
     else 
     return;              
}
int main()
{  
    node *root=NULL; 
        insertRec(root,10);  
        if(root !=NULL)  
            printf("\ndata=%d",root->data); //2nd printf
        insertRec(root,5);
        insertRec(root,15);
        insertRec(root,3);
        insertRec(root,18); 
        display(root);
        getch();
}

回答1:


You are passing root as value so changes made to root in insert function doesn't reflect at main function, hence root remains NULL in main function. To rectify your code, you need to pass Pointer to pointer. Pass address of root to reflect change in main function.

void insertRec(node *r, int num)

should be coded like:

void insertRec(node **r, int num)
{
    if(*r==NULL)
    {      
         *r= malloc(sizeof(node)); 
         (*r)->data=num; 

 // 

and use *root inside insert function.

And call it as insertRec(&root, 10); from main.

Additionally, if you allocates memory dynamically then you should free allocated memory using free explicitly.

One more thing learn Indenting C Programs.



来源:https://stackoverflow.com/questions/21495489/binary-search-tree-insertion-root-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!