二进制搜索树插入导致堆栈溢出C ++

时间:2015-04-08 19:20:15

标签: c++ binary-tree binary-search-tree

我正在尝试将值插入二叉搜索树。我有一个树的叶子类,以及一个集合本身的类。这是叶子的类:

template <class K, class T>
class BSTLeaf{
public:
    BSTLeaf(const K& k, const T& c);
    K key;
    T data;
    BSTLeaf * left;
    BSTLeaf * right;
    void insert(const K& k, const T& c);
private:
};

这是另一个按预期工作的类的插入函数:

template <class K,class T>
void BSTKeyedCollection<K,T>::insert(const K& k, const T& c){
    if(root != NULL){
        cout << "trying to insert " << c << endl;
        root->insert(k,c);
    }
    else{
        cout << "ROOT WAS NULL" << endl;
        root = new BSTLeaf<K,T>(k,c);
        cout << "The root node contains " << c << endl;
    }
}

以下是导致溢出的函数:

template <class K, class T>
void BSTLeaf<K,T>::insert(const K& k, const T& c){
    //if the key is less than the node it comes to
    if(k < key){
        if(left == NULL){
            left = new BSTLeaf<K,T>(k,c);
        }
        else
            insert(k,c);
    }
    if(k > key){
        if(right == NULL){
            right = new BSTLeaf<K,T>(k,c);
        }
        else
            insert(k,c);
    }

}

不确定构造函数是否有用,但现在是:

template <class K,class T>
BSTLeaf<K,T>::BSTLeaf(const K& k, const T& c){
    key = k;
    data = c;
    left = NULL;
    right = NULL;
};

我们可以假设K将始终是&lt;和&gt;将工作,这不是一个问题。该函数将在根处插入一个值,再插入一个值,然后溢出。在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您在同一个实例上调用相同的函数,导致堆栈溢出(对相同函数的循环调用)。我认为你的意思是left->insert(k,c);right->insert(k,c);

答案 1 :(得分:2)

看起来您的问题来自对insert的递归调用。你应该在当前叶子的右边或左边叶子上调用它:

template <class K, class T>
void BSTLeaf<K,T>::insert(const K& k, const T& c){
    //if the key is less than the node it comes to
    if(k < key){
        if(left == NULL){
            left = new BSTLeaf<K,T>(k,c);
        }
        else
            left->insert(k,c);
    }
    if(k > key){
        if(right == NULL){
            right = new BSTLeaf<K,T>(k,c);
        }
        else
            right->insert(k,c);
    }

}
相关问题