我在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;
}
答案 0 :(得分:2)
以下是对代码的轻微修改:
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) // We could put while(true) here.
{
r=rand(); // Modulo is a somehow slow operation
if((r & 1 )== 0) // This is much faster. It checks if r is even
{ cout<<"\nRandom is "<<r<<", which is even therefore we have to go to the right."<<endl;
if ( aux->right == NULL) // We found an empty spot, use it and break
{
aux->right = n; break;
}
else // else move to the right child and continue
{
aux=aux->right;
cout<<aux->getdata()<<endl;
}
}
else
{
cout<<"\nRandom is "<<r<<", which is odd Therefore we have to go to the left."<<endl;
if ( aux->left == NULL) // We found an empty spot, use it and break
{
aux->left = n; break;
}
else // else move to the left child and continue
{
aux=aux->left;
cout<<aux->getdata()<<endl;
}
}
}
cout<<"\nWe insert "<<n->getdata()<<endl;
}
主要原因是你误用了aux。这是一个例子,我希望能帮助你找出错误:
node * aux = head; // suppose head doesn't have any child node
node * n = new node(data);
aux = aux->left; // Set aux to point on the left child of head
aux = n; // Set aux to point on n
cout << aux == NULL?"Aux is null":"Aux is not null" << endl;
cout << head->left == NULL?"Left is null":"Left is not null" << endl;
这段代码回复:
Aux is not null
Left is null
原因是,当我们将 n 分配给辅助时,我们只是告诉辅助指向 n 而不是指向左侧节点。我们没有指定 n 作为头部的左孩子。
您也可以通过将aux声明为节点指针的指针来解决此问题。
node * * aux = &head;