Ali*_*Ali 3 c++ algorithm binary-search-tree
也许之前被问了几百万次,但我根本无法理解这有什么不对.我不想在互联网上使用任何代码,所以我只是试着编写我的想法.这个或我的打印功能是错误的.下面的代码有什么问题吗?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
temp=newNode;
Run Code Online (Sandbox Code Playgroud)
这会将指针指定给局部变量,该函数在函数返回时被丢弃,从而丢失新节点.相反,您希望将其分配给树中的指针; 也许是这样的:
if (temp->data < value) { // If the new node should be to the left
if (temp->left) { // If there is a left subtree
temp = temp->left; // Move into the left subtree
} else { // Otherwise
temp->left = newNode; // Insert the new node there
return; // Done.
}
}
Run Code Online (Sandbox Code Playgroud)
同样temp->right如果value < temp->data.
也:
if (temp->data == value)
return;
Run Code Online (Sandbox Code Playgroud)
那里有内存泄漏; 你应该delete newNode在回来之前.