For an assignment, I need to implement several functions of a binary search tree. I've gotten what seems like logical code, however, whenever I try and implement the insert node function, I get a program crash. Here is my code for the insert function:
void insert (K k, V v)
{
TreeNode<K,V> * treeNode = NULL;
TreeNode<K,V> *temp=NULL;
TreeNode<K,V> *prev=NULL;
temp = root;
while(temp) //This is the loop that causes a crash, even if I remove the loop.
{
prev = temp;
if (temp->key < treeNode->key)
temp = temp->right;
else
temp = temp->left;
}
if (prev==NULL)
root = treeNode;
else
{
if (prev->key<treeNode->key)
prev->right = treeNode;
else
prev->left = treeNode;
}
}
I'll also include the TreeNode class:
template <class K, class V> class TreeNode
{
public:
TreeNode(K k, V v): key(k), value(v), left(0), right(0) {}
K key;
V value;
TreeNode<K,V> *left;
TreeNode<K,V> *right;
template <class X, class Y> friend std::ostream & operator
<< (std::ostream &s,const TreeNode<X,Y> &t);
};
And when I try and execute the command t.insert("bob", "bobdata"); bam, immediate crash. I've commented out various parameters and discovered that the indicated section is the issue, although beyond that I'm stuck. It happens even if I remove the loop and only execute once, so I'm not getting stuck in infinity. I feel like it may have something to do with the fact that I'm passing strings, but I don't know for sure, and am not knowledgeable enough to fix it if this is the problem. Is there anyone that can tell me what I'm doing wrong here? Thanks so much!