Reputation: 15
I want to know this error why it is occupied!!!
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 ;
}
when I execute this code, than I expect that root's data is 10. but really, root is null. why is root null?
I don't know !!!!
please teach me!!!
Upvotes: 0
Views: 259
Reputation: 47814
root
is never updated in your Insert
method. The passed root
to method is not same as the member variable.
Do like following :
Tree->root = Tree->Insert(Tree->root, 10) ;
or pass address of root or use this->root =
everywhere inside the method.
Overall the design need to be revisited, I assume you want to play and learn
Also make sure you release the memory once you're done. Currently you have memory leaks, everywhere.
Upvotes: 1