'Getting a stackoverflow error even though I have an iterative funciton

So basically I am struggling with stack overflow error. I have a question that I should implement an AVL tree and a binary search tree and see the difference between them. I have no problem with AVL but while generating binary search tree I get stack overflow error. Program reads from a file which contains +90000 lines and inserts info to binary search tree. At first I had a recursive insert function which was like this:

template <class Comparable>
void BinarySearchTree<Comparable>::insert(const Comparable & inserThis, BinaryNode<Comparable> * & tree) const {
    if(tree == nullptr)
        tree = new BinaryNode<Comparable>(inserThis, nullptr, nullptr);
    else if(inserThis < tree->element)
        insert(inserThis, tree->left);
    else if(tree->element < inserThis)
        insert(inserThis, tree->right);
}

Then, I searched a little bit and decided to change my function to an iterative one which is like this:

template <class Comparable>
void BinarySearchTree<Comparable>::insert(const Comparable & inserThis, BinaryNode<Comparable> * & tree) const {    
    if(tree == nullptr) {
        tree = new BinaryNode<Comparable>(inserThis, nullptr, nullptr);
    }
    else {
        BinaryNode<Comparable> * temp = tree;
        bool noDuplicate = true;

        while(noDuplicate && (temp != nullptr)) {
            if(inserThis < temp->element) {
                if(temp->left == nullptr) {
                    temp->left = new BinaryNode<Comparable>(inserThis, nullptr, nullptr);
                    temp = nullptr;
                }
                else temp = temp->left;
            }
            else if(temp->element < inserThis) {
                if(temp->right == nullptr) {
                    temp->right = new BinaryNode<Comparable>(inserThis, nullptr, nullptr);
                    temp = nullptr;
                }
                else temp = temp->right;
            }
            else noDuplicate = false;
        }
    }
}

But still I get a stack overflow error, only difference is it lasts longer to get the error. How can I fix this, is there a way for this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source