turin21mre
Programmer
When trying to implement a Binary Search tree I have run into an error where the pointer accessing the top of the tree (node *T) is pointing to things it ought not be pointing to. I have run into a similar error in a previous program but was able to fix the problem by initializing the errant pointers to NULL however this has not worked in this situation. After running the debugger it seems that the pointer is not being initialized to NULL and thus the error. I am not confident in my abilities to work with a double pointer so I believe that is where the problem may be. here is a sample of my code with the error first occurring on the specified line in the insert function:
class BinaryTree
{
public:
struct node
{
int data;
node *Lchild;
node *Rchild;
};
BinaryTree();
void insert( node **, int );
void remove( node **, int );
void find( node *, int , node * );
void find_min( node *, node * );
node *T;
};
#include<iostream.h>
BinaryTree::BinaryTree()
{
T = NULL;
if (T != NULL)
cout<<"constructor didn't work";
}
// inserts a new node onto the proper position on the tree
void BinaryTree::insert( node **T, int data)
{
if (T == NULL)
{
*T = new node;
if (*T == NULL)
cout << "Not enough memory";
else
{
(*T) -> data = data;
(*T) -> Lchild = NULL;
(*T) -> Rchild = NULL;
}
}
//error occurs here
else if (data < (*T) -> data)
insert(&((*T) -> Lchild), data);
else if (data >(*T) -> data)
insert(&((*T) -> Rchild), data);
else;
//already in tree
}
...
class BinaryTree
{
public:
struct node
{
int data;
node *Lchild;
node *Rchild;
};
BinaryTree();
void insert( node **, int );
void remove( node **, int );
void find( node *, int , node * );
void find_min( node *, node * );
node *T;
};
#include<iostream.h>
BinaryTree::BinaryTree()
{
T = NULL;
if (T != NULL)
cout<<"constructor didn't work";
}
// inserts a new node onto the proper position on the tree
void BinaryTree::insert( node **T, int data)
{
if (T == NULL)
{
*T = new node;
if (*T == NULL)
cout << "Not enough memory";
else
{
(*T) -> data = data;
(*T) -> Lchild = NULL;
(*T) -> Rchild = NULL;
}
}
//error occurs here
else if (data < (*T) -> data)
insert(&((*T) -> Lchild), data);
else if (data >(*T) -> data)
insert(&((*T) -> Rchild), data);
else;
//already in tree
}
...