我在 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;
}