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

标签 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 将始终是 < 和 > 适用的类型,因此这不是问题。该函数将在根部插入一个值,再插入一个值,然后溢出。在此先感谢您的帮助!

最佳答案

看起来您的问题来自于对 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);
    }

}

关于c++ - 二进制搜索树插入导致堆栈溢出 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29523505/

相关文章:

c - 在c中绘制二叉树到控制台

c - 如何在二叉树中搜索与给定值 x 的匹配项?

java - 如何将元素列表添加到二叉搜索 TreeMap 中?

c++ - 删除二叉搜索树的根节点

c - 如何逐行读取.txt文件到二叉搜索树

c++ - 捕获 Visual Studio 响应文件?

java - 从代数表达式创建二叉树

c++ - OpenCV/C++ - 从视频文件读取的帧在视频结束后重新启动

c++ - 尝试理解简单的大数计算

C++ - OpenGL 在 glDrawElements() 上崩溃