[英]Binary Search Tree insert causing a stack overflow C++
我正在尝试将值插入二叉搜索树。 我有一个用于树的叶子的类,还有一个针对集合本身的类。 这是叶子的类:
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始终是<和>适用的类型,所以这不是问题。 该函数将在根处插入一个值,再插入一个值,然后溢出。 先谢谢您的帮助!
您正在所在的同一实例上调用同一函数,从而导致堆栈溢出(对同一函数的循环调用)。 我认为您的意思是left->insert(k,c);
和right->insert(k,c);
。
看来您的问题来自于对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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.