问题
I am trying to finish the delete function.
Here is the pseudo code, notice the end:

I don't know if the pseudo code is wrong though.
Here is how I interpreted it:
Node* minNode = Minimum(toDelete->right);
int tmp = 0;
tmp = minNode->val;
// delete(&tmp);
free(minNode);
minNode=NULL;
toDelete->val=tmp;
except once it deletes it, it starts filling a trillion zeroes when printing.
Is what I am doing making sense? The rest of the code I have is right, or I think so anyway. It only screws up in this scenario.
Here's the minimum function as well
Node* BST::Minimum(Node *curr) {
// if (curr->left != NULL) {
// return(Minimum(curr->left));
// }
// return curr;
Node* node = curr;
while (node->left != NULL) {
node = node->left;
}
return node;
}
回答1:
That is some terrible pseudocode, and at a glance it didn't even look right (if this is a binary search tree, as BST
would indicate, then the circled part is wrong). There is much better information about binary search trees available on the internet.
At any rate, you're trying to find the smallest element in the right subtree, since that will be less than all the other elements in the right subtree but greater than all the other elements in the left subtree.
Looks like your minimum function is right. You need to delete the reference to minNode after you free it. So (minNode->parent)->left
= NULL or something slightly more tedious if you don't have a parent pointer. Right now that left
just points to an empty space in memory, leading to completely random behavior.
来源:https://stackoverflow.com/questions/13822032/tree-delete-node