I have to insert a node in a binary search tree. This is what i wrote for the InsertNode() method. But it keeps producing segmentation fault when i run the program. I couldnot find anything wrong in the code.
The constructor for TreeNode(int x) sets the item to x, leftchild and rightchild to NULL. So I guess nothings wrong with the TreeNode. Plz help.
void BST::InsertNode(int x)
{
TreeNode *parent = NULL;
TreeNode *child;
child = root;
while(child != NULL)
{
parent = child;
if(x <= child->getItem())
child = child->getLeftChild();
else
child = child->getRightChild();
}
if(parent == NULL)
{
child = new TreeNode(x);
root = child;
}
else if( x <= child->getItem())
{
child = new TreeNode(x);
parent->setLeftChild(child);
}
else
{
child = new TreeNode(x);
parent->setRightChild(child);
}
}