I am trying to write an algorithm to insert new nodes into a binary tree. My program crashes and I can't figure out why. My logic and syntax seem correct. Any help is greatly appreciated!
I have a data structure defined as TreeNode. It contains: int key, some other data fields, and TreeNode *left; TreeNode *right; root is a pointer to the root of the tree, it is part of the class MyTree, and newNode is a pointer to a TreeNode structure filled with data and ready to be inserted.
void MyTree::Insert(TreeNode *newNode)
{
TreeNode *temp = root; *back = NULL;
//Checking for inserting first node in the tree
if( root == NULL)
{
root = new MyTree(newNode); //this I feel might be the problem but I'm not sure how to fix it.
return;
else //Search for the location in tree to attach the new node
{
while(temp !=NULL)
{
back = temp;
if(temp ->key > newNode->key
temp = temp -> left;
else
temp = temp -> right;
}
//Determine which side to attach the new node to
if(back =NULL)
{
back -> left = newNode;
else
back -> right = newNode;
}