随机二叉树中的插入函数
Insertion function in a random binary tree
我在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;
}
以下是对代码的轻微修改:
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;
}
主要原因是您滥用了辅助设备。这里有一个例子,我希望能帮助你识别你的错误:
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 分配给 aux 时,我们只是告诉 aux 指向 n 而不是指向左侧节点。我们没有指定n作为头部的左子。
您还可以通过将 aux 声明为节点指针的指针来解决此问题。
node * * aux = &head;
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 当我尝试在 Main 中调用插入函数时,它不是取数字?
- 为 std::vector 编写自定义插入函数
- 类数组插入函数
- 需要帮助将字符串插入函数
- 在 C++ 中为特定哈希表创建插入函数
- 为sLinkedList编写插入函数时引发异常
- 无法转换字符串插入函数的参数
- 错误表达式必须是插入函数(二叉树 C++)中的可修改 Ivalue
- 具有 4 个指针的节点的递归插入函数返回 null
- 在字符串中的字符前添加空格C++插入函数
- "<某些系统标头>:错误:"<在此处插入函数>"在移动源文件后不是"std"的成员
- 自己的C++列表类实现(插入函数)出现问题
- 是否有任何快捷键可以插入函数的定义
- 使用算法中的插入函数将元素插入空容器中,未给出预期的结果
- 如何改进单向链表插入函数 - C++
- 在 QString 插入函数中使用参数
- 如何在LLVM传递中的模块末尾插入函数调用?
- 使用模板的插入函数会丢失数字
- Bool排序的插入函数,检查列表中是否已经存在int