[英]Binary Search Tree Forgetting Every Node I Add
My problem is seemingly simple, but I can't find its solution. 我的问题看似简单,但找不到解决方案。 I have a binary tree, and this is my add function: 我有一棵二叉树,这是我的添加函数:
void collection::addToTree(vendor *& item)
{
Node * curr = root;
while (curr)
{
if (strcmp(item->getName(), root->item->getName()) < 0)
curr = curr->left;
else
curr = curr->right;
}
curr = new Node(item);
}
And this is my Node
constructor: 这是我的Node
构造函数:
collection::Node::Node(vendor *& item) : left(nullptr), right(nullptr)
{
this->item = item;
}
However, the tree is always empty, no matter what or how many items I try to add to it. 但是,无论我尝试添加多少个项目,树总是空的。 The only other piece of code I can think of that will help you guys is my struct
for my tree: 我可以想到的,这将帮助你们唯一的另一段代码是我的struct
为我的树:
struct Node
{
Node();
Node(vendor *& item);
vendor * item;
Node *left, *right;
};
Node * root;
All of the sub-variables of vendor
do have values (as I've seen in my debugger). vendor
所有子变量都具有值(如我在调试器中看到的)。 I wish I could give you guys more detail, but this is all I know about the error. 希望我能为您提供更多详细信息,但这只是我对错误的了解。 Any feedback is greatly appreciated. 任何反馈,不胜感激。
在add
函数中,您仅使curr
指向新项,但这并不会变回先前的左/右指针,这可能正是您的目标。
You need to modify the left/right pointers directly, something like this: 您需要直接修改左右指针,如下所示:
void collection::addToTree(vendor *& item)
{
Node * curr = root;
while (curr)
{
if (strcmp(item->getName(), curr->item->getName()) < 0)
{
if (!curr->left)
{
curr->left = new Node(item);
return;
}
curr = curr->left;
}
else
{
if (!curr->right)
{
curr->right = new Node(item);
return;
}
curr = curr->right;
}
}
root = new Node(item);
}
Also, make sure you do Node * root = nullptr
, as no initializing it can lead to it containing any arbitrary value. 另外,请确保执行Node * root = nullptr
,因为不进行初始化可能会导致它包含任意值。
Notice that I also changed if (strcmp(item->getName(), root->item->getName()) < 0)
to if (strcmp(item->getName(), curr->item->getName()) < 0)
, as the branching is dependent on curr
, not root
. 注意我也将if (strcmp(item->getName(), root->item->getName()) < 0)
更改为if (strcmp(item->getName(), curr->item->getName()) < 0)
,因为分支取决于curr
而不是root
。
I think the problem here is that your curr
variable should be declared as Node **curr
and receive the root's address in order for the change to be visible outside of the addToTree
function. 我认为这里的问题在于,您的curr
变量应声明为Node **curr
并接收根的地址,以便在addToTree
函数之外可以看到更改。
void collection::addToTree(vendor *& item)
{
Node ** curr = &root;
while (*curr)
{
if (strcmp(item->getName(), (*curr)->item->getName()) < 0)
(*curr) = (*curr)->left;
else
(*curr) = (*curr)->right;
}
*curr = new Node(item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.