c++ - This code looks like it deletes this object but it doesnt? -
the following code removing node of binary tree. have stepped through code , i'm pretty sure problem lies in last "else if" in destroy(). i'm trying replace given node smallest node delete given node. remove() , findsmallest work should think. when reprint tree no changes have been made.i'm beginner, hints/help appreciated!
void remove(key k) { remove(k, root); } void remove(key k, binarysearchtreenode<key, value> * n) { if (n) { if (root->key == k) removeroot(); else { //1 child if ( (n->left != nullptr) && (k < n->key) ) { if (k == n->left->key) destroy(n->left, true); else remove(k, n->left); } else if (n->right && k > n->key ) { if (k == n->right->key) destroy(n->right, false); else remove(k, n->right); } else { cout << "no remove\n"; } } } else cout << "trww empty"; } void destroy(binarysearchtreenode<key, value> * n, bool isleft) { if (n == nullptr) { return; } else if (!n->left && !n->right) { n->left = nullptr; n->right = nullptr; n->parent = nullptr; delete n; n = nullptr; } else if (!n->left && n->right) { isleft ? n->parent->left = n->right : n->parent->right = n->right; cout << "killing " << n->key << endl; n->parent = nullptr; n->left = nullptr; n->right = nullptr; delete n; n = nullptr; } else if (n->left && !n->right) { isleft ? n->parent->left = n->left : n->parent->right = n->left; cout << "killing " << n->key << endl; n->parent = nullptr; n->left = nullptr; n->right = nullptr; delete n; n = nullptr; } /* program goes code below*/ else if (n->left && n->right) { binarysearchtreenode<key, value> * small = findsmallest(n->right); if (isleft) n->parent->left = small; else n->parent->right = small; small->parent = n->parent; small->left = n->left; small->right = n->right; n->parent = nullptr; n->left = nullptr; n->right = nullptr; //key smallkey = small->key; //value smallvalue = small->value; cout << "killing " << n->key << endl; delete n; n = nullptr; } else cout << "fail"; } binarysearchtreenode<key, value> * findsmallest(binarysearchtreenode<key, value> * n) { if (!n) return part; else { if (n->left) return findsmallest(n->left); else return n; } }
you give node destroy()
pointer. means can things did, except change variable in calling method.
when n= nullptr;
in destroy()
changes local variable. doesn't change calling variable, example n->right
nullptr
still point place deleted object was.
if set parameter reference pointer (*&
) can change calling variable , remove pointer node.
the reason why looks original tree because memory allocated deleted node happened not reused yet. later , tree cause access wrong pointer , maybe crash. behaviour undefined.
Comments
Post a Comment