我正在制作我的删除功能,所以首先我试图找到父节点,但我一直遇到一个seg错误。当父母有2个孩子,但是当它有一个孩子时,它会崩溃。我一直试图改变现状,但我无法弄明白,有人可以帮助我。
Node* BST::getParentNode(int value){
Node* temp = new Node;
temp = _root;
while (temp != NULL){
Node* left = temp->getLeft();
Node* right = temp->getRight();
if (left->getData() == value)
return temp;
if (right->getData() == value)
return temp;
if (right->getData() > value){
temp = temp->getRight();
}
else{
temp = temp->getLeft();
}
}
Node* empty = new Node;
empty = NULL;
return empty;
}
答案 0 :(得分:0)
在访问之前,您没有检查左右指针是否为空。请参阅下面的评论
Node* BST::getParentNode(int value){
// Node* temp = new Node; // This line isn't needed...
Node* temp = _root;
while (temp != NULL){
Node* left = temp->getLeft();
Node* right = temp->getRight();
if(NULL != left) { // You are missing this check. I'm assuming this can happen
// because it's part of your exit condition from the while loop
if (left->getData() == value)
return temp;
}
if(NULL != right) { // You are also missing this check. You can't call function on
// null pointers...
if (right->getData() == value)
return temp;
}
if (right->getData() > value){
temp = temp->getRight();
}
else{
temp = temp->getLeft();
}
}
// It's unclear what you're trying to do on the next three lines
// you create an object with new, then throw the memory away by assigning the
// pointer to NULL
Node* empty = new Node;
empty = NULL;
return empty; // With the code as is, you might as well return NULL;
// which would also get rid of the memory leak...
}