Maybe asked million times before but I simply cannot understand what’s wrong with this. I didn’t want to use any code on the internet so I’ve just tried to program what’s on my mind. Either this or my print function is wrong. Is there anything wrong with the code below?
void addNode(int value)
{
Node* newNode=new Node;
newNode->data=value;
if(root==NULL)
root=newNode;
else {
Node* temp=root,*parent;
while(temp!=NULL)
{
parent=temp;
if(temp->data == value)
return;
else if(temp->data < value)
temp=temp->left;
else
temp=temp->right;
}
temp=newNode;
}
}
This assigns the pointer to a local variable, which is discarded when the function returns, losing the new node. Instead, you want to assign it to a pointer within the tree; perhaps something like:
and likewise for
temp->rightifvalue < temp->data.Also:
You have a memory leak there; you should
delete newNodebefore returning.