Ok so let's say I have a pointer of type TreeNode called root. This pointer points to the beginning of my binary search tree(http://imgur.com/MqVhJ) and to reach the bottom of my tree I could manually do something like this root->leftChild->rightChild->item but I know that's not ideal. So I've made a loop that looks something like this: for(TreeNode *treeNodePtr = root; root != NULL; ){}
My question is, when I reach the desired TreeNode in my loop, how do I actually affect my tree? That is, I want to change or delete a TreeNode when my treeNodePtr points to the TreeNode that is desired by doing something like this:
1 2 3 4
// treeNodePtr points to the node in the tree which I want to alter
//exchanging the right child of this tree with its parent
treeNodePtr = treeNodePtr->rightChildPtr;
Ok, well I have an assignment for school that asks me to implement an iterative version of deleting a node from the tree. So I'm using a loop to go through the tree until I find the node. This is where the for(TreeNode *treeNodePtr = root; root != NULL; ){} comes into play. So once treeNodePtr == the node im looking for, I want to delete that node. In my head I'm thinking I should delete the node by replacing what it currently is with its leftmost child. I do this by: treeNodePtr = treeNodePtr->leftChildPtr;
But back to my original question...When treeNodePtr points to the node wish needs to be deleted, how do I actually take it out of my tree? Altering treeNodePtr doesn't affect the tree with what I've tried.
Oh, okay. In that case you just have to delete what's at the end of your search. So if the treeNodePtr->Right is what you want to delete you would just do this:
1 2 3 4 5
delete treeNodePtr->Right;
treeNodePtr->Right = NULL; //Set it back to NULL so that you know it doesn't point anywhere
//Doing this is not a good idea:
delete treeNodePtr; //since the node's parent won't know it was deleted.
Just make sure that if Right is not actually a leaf node, and has it's own children, that these get taken care of by Right's destructor. Otherwise you will have a memory leak.
How are you identifying which node you want to delete? Does each node have a key? Hold a special value? Cover an area? Or are you simply looking for a node which doesn't point anywhere else?