我正在尝试用c ++创建一个简单的二叉搜索树类,但每当我调用我的插入函数时:
template<typename T>
void BSTree_Fast<T>::insert(T & key)
{
cout<<"working";
int i=0;
BSTNode<T> *newNode=new BSTNode<T>(key); //Initializing pointer to newNode with key as Key
if(maxDepth==0){ //if tree is empty, sets root to new node
root=newNode;
setMaxDepth(1);
}
BSTNode<T> *curr=root; //Traversal unit curr
if(key==curr->getKey()){ //checking if inserted key is same as root key
int n=curr->getNum();
n++;
curr->setNum(n);
delete(newNode);
}
while(key!=curr->getKey()){ //first while loop when above is not true
if(key<curr->getKey()){ //checks left if key < current key
if(curr->getLeft()==NULL){ //if cannot traverse left, creates new node to left of current
curr->setLeft(newNode);
if(i>maxDepth){
cout<<i;
setMaxDepth(i);
}
break;
}
else if(curr->getLeft()->getKey()==key){//if left child equals input key, increase number
int n=curr->getLeft()->getNum();
n++;
curr->getLeft()->setNum(n);
delete(newNode);
break;
}
else{
i++;
curr=curr->getLeft(); //traverses left
}
}
if(key>curr->getKey()){ //checks right if key > current key
if(curr->getRight()==NULL){ //if cannot traverse right, creates new node to right
curr->setRight(newNode);
if(i>maxDepth){
setMaxDepth(i);
}
break;
}
else if(curr->getRight()->getKey()==key){//if right child equals input key, increase number
int n=curr->getRight()->getNum();
n++;
curr->getRight()->setNum(n);
delete(newNode);
break;
}
else{
i++;
curr=curr->getRight(); //traverses to right
}
}
}
}
然而,在通过从文件读入字符串来调用任何实际代码之前,它似乎遇到了段错误。
答案 0 :(得分:4)
完成添加第一个节点的过程:
BSTNode<T> *newNode=new BSTNode<T>(key); //Initializing pointer to newNode with key as Key
if(maxDepth==0){ //if tree is empty, sets root to new node
root=newNode;
setMaxDepth(1);
}
哦,哦,这里没有return
。因此,在我们设置root=newNode
后,我们继续。
BSTNode<T> *curr=root; //Traversal unit curr
if(key==curr->getKey()){ //checking if inserted key is same as root key
int n=curr->getNum();
n++;
curr->setNum(n);
delete(newNode);
}
显然钥匙会匹配。我们刚刚删除了newNode
,同时也是root
和cur
。
while(key!=curr->getKey()){
哎呀,我们访问了刚删除的curr
。