2

我尝试实现 BST 程序,但由于运行时错误,执行失败。请告诉我如何纠正它。我创建树的代码是:

struct node *createBinTree()
{ int val,size;
   struct node *bintree, *newnode;
   bintree= NULL;
   printf("Enter the values of nodes terminated by a negetive no.\n");
   val=0;
   while(val>=0)
   {
     printf("\nEnter value");
     scanf("%d",&val);
     if(val>=0)
     { newnode = (struct node*)sizeof(struct node);
    newnode->val=val;
    newnode->lchild= NULL;
    newnode->rchild= NULL;
    bintree=attach(bintree,newnode);
     }
   }
   return bintree;
   }
   struct node *attach(struct node *tree,struct node* tnode)
   {if(tree==NULL)
     tree=tnode;
     else{
     if(tnode->val<tree->val)
      tree->lchild= attach(tree->lchild,tnode);
      else
      tree->rchild= attach(tree->rchild,tnode);

   }
   return tree;
  }
4

2 回答 2

0
newnode = (struct node*)sizeof(struct node);

malloc()在 while 循环的上述行中缺少

用这个 :

newnode = (struct node*)malloc(sizeof(struct node)); 
于 2012-11-12T07:02:41.710 回答
0
newnode = (struct node*)sizeof(struct node);

这不是您创建节点的方式。您没有使用malloc或忘记将其包含在您的代码中。相反,您直接为其分配一个地址,这是不推荐的。将其更改为使用malloc,您应该没问题。

于 2012-11-12T06:56:25.467 回答