この C++ のバイナリ ツリーの挿入関数に問題があります。右または左にノードを再度追加する必要があるまで、ノードは正しく挿入されます。関数は、私がすでにそれらの場所にノードを挿入している場合、左または右のいずれにもノードがないと考えています。
これが私のコードです:
void insert(string data)
{
srand(time(NULL));
int r;
node *aux=head;
node *n=new node(data);
if (head==NULL)
{
head =n;
return;
}
while (aux!=NULL)
{
r=rand()%100;
if (r>50)
{
cout<<"\nRandom is "<<r<<", Therefore we have to go to the right."<<endl;
aux=aux->right;
}
else
{
cout<<"\nRandom is "<<r<<", Therefore we have to go to the left."<<endl;
aux=aux->left;
if (aux!=NULL)
{
cout<<aux->getdata()<<endl;
}
}
}
aux=n;
cout<<"\nWe insert "<<aux->getdata()<<endl;
}