I am new to C++ and I can't find why the root of the tree changes whenever I add anything to the tree. It must be a pointer problem but I can't figure it out. For example:
BST bst;
bst.insert(5);
bst.insert(2);
I get the correct output when I insert 5, but when I insert 2 it says:
Inserted 2 to the left of 2.
Node class:
class Node
{
// Let BST directly access members.
friend class BST;
public:
// Constructor
Node(int i);
int getValue();
protected:
int value;
Node *left;
Node *right;
};
// Constructor
Node::Node(int i)
{
value = i;
left = 0;
right = 0;
}
int Node::getValue()
{
return value;
}
BST class:
class BST
{
public:
BST();
void insert(int i);
void print();
void print(Node *n);
private:
// root of the tree
Node *root;
};
BST::BST()
{
root = 0;
}
void BST::insert(int i)
{
Node *cur = this->root;
Node *prev;
Node new_node(i);
if(cur == 0)
{
this->root = &new_node;
cout << "Root is empty, insert " << this->root->value << " as root." << endl;
return;
}
while(cur != 0)
{
prev = cur;
if(i <= cur->value)
{
cur = cur->left;
if(cur == 0)
{
prev->left = &new_node;
cout << "Inserted " << prev->left->value << " to the left of " << prev->value << endl;
return;
}
}
else if(i > cur->value)
{
cur = cur->right;
if(cur == 0)
{
prev->right = &new_node;
cout << "Inserted " << prev->right->value << " to the right of " << prev->value << endl;
return;
}
}
}
}
void BST::print()
{
print(this->root);
}
void BST::print(Node *n)
{
if(n == 0)
{
return;
}
print(n->left);
cout << n->value << " " << endl;
print(n->right);
}
Thanks.
insertmethod and they are deleted as soon as your code exit it. It might be unrelated to your issue but it will bite you anyway later on.Node new_node(i)was enough in C++ to create the object. Thanks.