[英]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.