// So I call this function after deleting a node.
// It works before I delete the node, but for some reason
// after I perform a deletion and update the tree it runs into
// EXC_BAD_ACCESS on the line below...
void BinaryTree::updateCost(BinaryNode *root) {
if (root != NULL)
root->updateCostRecursively(1);
}
void BinaryNode::updateCostRecursively(int newCost) {
cout << this << endl; // prints 0x3000000000000000 before the bad access
cost = newCost; // has a bad access here
if (right != NULL)
right->updateCostRecursively(newCost + 1);
if (left != NULL)
left->updateCostRecursively(newCost + 1);
}
爲什麼在NULL對象上調用這個遞歸函數,即使每次都檢查指針?爲什麼在NULL檢查之後會在指針上調用遞歸函數?
我已經複製了我用來刪除下面節點的代碼。我仍然無法理解遞歸函數,但是從什麼時候我都可以告訴我離開一個懸掛的指針。
BinaryNode *BinaryTree::findMin(BinaryNode *t) {
if (t == NULL) return NULL;
while (t->left != NULL) t = t->left;
return t;
}
BinaryNode *BinaryTree::removeMin(BinaryNode *t) {
if (t == NULL) return NULL;
if (t->left != NULL)
t->left = removeMin(t->left);
else {
BinaryNode *node = t;
t = t->right;
delete node;
}
return t;
}
bool BinaryTree::remove(int key) {
if (root != NULL && remove(key, root))
return true;
return false;
}
BinaryNode *BinaryTree::remove(int x, BinaryNode *t) {
if (t == NULL) return NULL;
if (x < t->key)
t->left = remove(x, t->left);
else if (x > t->key)
t->right = remove(x, t->right);
else if (t->left != NULL && t->right != NULL) {
// item x is found; t has two children
t->key = findMin(t->right)->key;
t->right = removeMin(t->right);
} else { //t has only one child
BinaryNode *node = t;
t = (t->left != NULL) ? t->left : t->right;
delete node;
}
updateCost(root);
return t;
}
因爲它不是NULL?請注意'delete'不會修改指針。如果這不是問題,那麼請構建一個[最小測試用例](http://sscce.org)。 – 2013-03-19 22:16:35
0x3000000000000000!= 0 – fbafelipe 2013-03-19 22:17:23