【问题标题】:Binary search tree insertion - root always null二叉搜索树插入 - 根始终为空
【发布时间】:2014-02-25 01:23:22
【问题描述】:

我有使用递归在二叉搜索树中插入值的 ds 代码。问题是根始终保持为空。 执行时,第一个 printf() 打印 10,但第二个 printf(在 insertRec(10) 之后)不打印任何内容,因为 root 为 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();
}

【问题讨论】:

    标签: c binary-search-tree insertion


    【解决方案1】:

    您将root 作为值传递,因此在插入函数中对root 所做的更改不会反映在主函数中,因此root 在主函数中仍为NULL。要更正您的代码,请need to pass Pointer to pointer。传递root 的地址以反映主函数的变化。

    void insertRec(node *r, int num)
    

    应该这样编码:

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

    并在插入函数中使用*root

    并从 main 中将其称为 insertRec(&amp;root, 10);

    此外,如果您动态分配内存,那么您应该使用 free 显式释放分配的内存。

    再学一件事Indenting C Programs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      相关资源
      最近更新 更多