Hi guys, ive been working on a BST and during insert, the root seems to change for no reason that I can see. Maybe you guys can help me out?
heres the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
void BinarySearchTree::insertTreeNode(Student* obj)
{
TreeNode *newNode= new TreeNode(obj);
TreeNode *nodePtr=NULL;
if(root==NULL)
{
root=newNode;
height=1;
cout << "New Root" << root->data->pin << endl;
return;
}
else
{
cout << "Send root" << root->data->pin << endl;
cout << "Send newNode" << newNode->data->pin << endl;
cout << height << endl;
nodePtr=compare(newNode,root);
if(newNode->data->pin<=nodePtr->data->pin)
{
nodePtr->leftChild=newNode;
}
else
{
nodePtr->rightChild=newNode;
}
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
TreeNode* BinarySearchTree::compare(TreeNode*newNode, TreeNode*currNode)
{
cout << newNode->data->pin << endl << currNode->data->pin << endl;
if(newNode->data->pin<=currNode->data->pin)
{
if(currNode->leftChild==NULL)
{
return currNode;
}
compare(newNode,currNode->leftChild);
}
else
{
if(currNode->rightChild==NULL)
{
return currNode;
}
compare(newNode,currNode->rightChild);
}
}
|
Edit:The output looks like this:
/*Enter filename to open: gpa.txt
New Root3800
Send root4200
Send newNode4200
1
4200
4200
Press any key to continue . . .
*/
I put the cout in the insert function just so i can see what is being passed.
On my second insertion, these two lines
cout << "Send root" << root->data->pin << endl;
cout << "Send newNode" << newNode->data->pin << endl;
will output the same pin even though they are different. I dont know why root is being changed to the newNode's data
Any help is appreciated. Thanks