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:
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 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). 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.
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
.
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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.