我想知道这个错误为什么被占用!!!
class node
{
public:
int data ;
node *left ;
node *right ;
} ;
class tree
{
public:
node * root ;
public:
tree()
{
root = NULL ;
}
node* Insert(node* root, int num) //
{
if(root == NULL) // root is null
{
node * temp = new node() ;
temp->left = NULL ;
temp->right = NULL ;
temp->data = num ;
root = temp ;
}
else if ( num < root->data )
{
root->left = Insert(root->left, num ) ;
}
else if ( num > root->data)
{
root->right = Insert(root->right, num ) ;
}
return root ;
}
} ;
void main()
{
tree * Tree = new tree() ;
Tree->Insert(Tree->root, 10) ;
cout << temp->root->data ;
}
当我执行这段代码时,我预计 root 的数据是 10。 但实际上,根是空的。 为什么 root 为空?
我不知道!!!!
请教我!!!
最佳答案
root
永远不会在您的 Insert
方法中更新。传递给方法的 root
与成员变量不同。
喜欢以下内容:
Tree->root = Tree->Insert(Tree->root, 10) ;
或传递根地址或在方法内的任何地方使用this->root =
。
总体而言,需要重新审视设计,我假设您想边玩边学
还要确保在完成后释放内存。目前到处都有内存泄漏。
关于c++ - 来自 C++ 的 BST 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37289406/