N
Nick Kiguta
I have two classes, a Node class and a Bstree class. The Bstree class
contains a pointer to a Node class as one of its private members. Now I
need to build a binary search tree from multiple objects of the Node
class. I have a function addNode which is defined as follows
void Bstree::addNode ( Node **start, int val )
{
if( *start == NULL ) //if bst empty
{
*start = new Node ( val );
}
else //if bst not empty
{ //val is less than current nodes value
if( val < (*start)->getValue() )
{
Node * pLeft = ((*start)->getLeftPtr());
addNode ( &pLeft, val );
}
//val is greater than current nodes value
else if( val > (*start)->getValue() )
{
Node *pRight = ((*start)->getRightPtr());
addNode ( &pRight, val );
}
else{
cout <<"Duplicate data. IGNORED!!"<<endl;
}
}
}
When I call this function in my main program, I am calling it this way.
cout<<"Enter a number to add to the binary tree"<<endl;
cin >> num;
Node* temp = btree.getRoot();
btree.addNode ( &temp, num );[/highlight]
Function getRoot() returns the root pointer of type class Node which is
a private member of class Bstree. However, when I try to print the
tree, I get memory errors. Its as if the left or right pointers dont
have any values/as if they are null yet I am inputting values in them.
I have tried since this morning and still cant get it. This is my first
C++ assignment. Any help is greatly appreciated.
contains a pointer to a Node class as one of its private members. Now I
need to build a binary search tree from multiple objects of the Node
class. I have a function addNode which is defined as follows
void Bstree::addNode ( Node **start, int val )
{
if( *start == NULL ) //if bst empty
{
*start = new Node ( val );
}
else //if bst not empty
{ //val is less than current nodes value
if( val < (*start)->getValue() )
{
Node * pLeft = ((*start)->getLeftPtr());
addNode ( &pLeft, val );
}
//val is greater than current nodes value
else if( val > (*start)->getValue() )
{
Node *pRight = ((*start)->getRightPtr());
addNode ( &pRight, val );
}
else{
cout <<"Duplicate data. IGNORED!!"<<endl;
}
}
}
When I call this function in my main program, I am calling it this way.
cout<<"Enter a number to add to the binary tree"<<endl;
cin >> num;
Node* temp = btree.getRoot();
btree.addNode ( &temp, num );[/highlight]
Function getRoot() returns the root pointer of type class Node which is
a private member of class Bstree. However, when I try to print the
tree, I get memory errors. Its as if the left or right pointers dont
have any values/as if they are null yet I am inputting values in them.
I have tried since this morning and still cant get it. This is my first
C++ assignment. Any help is greatly appreciated.