简体   繁体   English

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

[英]Binary Search Tree insert causing a stack overflow C++

I am trying to insert values into a binary search tree. 我正在尝试将值插入二叉搜索树。 I have a class for the leaves of the tree, and a class for the collection itself. 我有一个用于树的叶子的类,还有一个针对集合本身的类。 Here is the class for the leaves: 这是叶子的类:

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:
};

Here is the insert function for the other class that is working as intended: 这是按预期工作的其他类的插入函数:

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;
    }
}

Here is the function that is causing the overflow: 这是导致溢出的函数:

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);
    }

}

Not sure if the constructor would be helpful but here it is: 不知道构造函数是否会有所帮助,但在这里是:

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

We are allowed to assume that K will always be a type that < and > will work for so that is not an issue. 我们可以假定K始终是<和>适用的类型,所以这不是问题。 The function will insert a value at the root, insert one more value, and then overflow. 该函数将在根处插入一个值,再插入一个值,然后溢出。 Thanks in advance for the help! 先谢谢您的帮助!

You are calling the same function on the same instance you are in, causing a stack overflow (cyclical calls to the same function). 您正在所在的同一实例上调用同一函数,从而导致堆栈溢出(对同一函数的循环调用)。 I think you meant left->insert(k,c); 我认为您的意思是left->insert(k,c); and right->insert(k,c); right->insert(k,c); .

Looks like your problem is coming from the recursive call to insert . 看来您的问题来自于对insert的递归调用。 You should call it on the right or left leaf of the current leaf: 您应该在当前叶子的右侧或左侧叶子上调用它:

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);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM