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、ここのコードに含めるのを忘れています。代わりに、アドレスを直接割り当てることになりますが、これは決してお勧めできません。これを使用するように変更するmallocと、問題ないはずです。

于 2012-11-12T06:56:25.467 に答える
0
newnode = (struct node*)sizeof(struct node);

malloc()whileループのこの上記の行に欠けています

これを使って :

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