void Btree::insert(int x)
{
Node * n = new Node; // create a new node and init it
n->data = x;
n->left = 0;
n-> right = 0;
current = root; // set current node to root
if(root != 0)
{
current = root; // set current node to root again
while(current != 0) // loop until current is null
{
if(current->data < x)
{
current = current->left;
}
else
{
current = current->right;
}
}
n = current; // set new node pointer to null (the value we know current to be) :-(
} // so the new node hasn't been added to tree; instead memory has been leaked
else
{
root = n; // set root to point at new node :-)
}
}
I take it that you want your new node to be added to the existing tree? If so, you need to find an unused left or right member to point at your new node (so exiting the while loop when current == 0 is too late.)
And current prob shouldn't be a member variable given the way it's being used in your insert method. (Based on current code it should be declared on line 57)
Oh, and if you're compiler is up to date enough, you should use nullptr rather than 0 to test if a pointer against null.
Create a constructor for your Node class: Node(int d) : data(d), left(NULL), right(NULL) {}
Instead of keeping a pointer to the current node, keep a pointer to the current link - in other words, a pointer to root, or the left/right pointer of a node. If you do this, then you don't need a special case for when root == NULL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void
Btree::insert(int x)
{
Node *n = new Node(x); // use new constructor
Node **link = &root;
Node *cur;
while (cur = *link) {
if (cur->data < x) {
link = &cur->left;
} else {
link = &cur->right;
}
}
*link = n;
}