Binary search tree insertion - root always null

前端 未结 1 921
名媛妹妹
名媛妹妹 2021-01-22 01:43

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

相关标签:
1条回答
  • 2021-01-22 02:25

    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.

    0 讨论(0)
提交回复
热议问题