delete by copy only for non-children nodes?
Hello yet again! This is a different problem with the same project, so I thought I'd create a new thread. Anyways, the project is to: create a binary tree randomly, then delete elements either assymetrically or symmetrically, and keep track of the difference between IPL and APL for the two (path lengths)- (the difference is that in assymetric deletion, successor and predecessor nodes are alternately deleted, keeping the tree in order - I used a static global int to do this, and just decrement/increment after each pass). Anyways, the problem is this: my deleteByCopy() function, which I took right out of the data structs book, will work once or twice, then kaboom! I suspected the error was: deleteByCopy() is designed for nodes with children, and with the probability of a randomly-chosen node being a leaf at about 50% in a complete tree, it was trying to perform operations which made it crash with a leaf node. Anyways, I tried to remedy that, as you can see below, by
Code:
if(node->left == 0 && node->right == 0)
delete node;//also tried delete tmp
but it didn't work (no surprise there, I figured it was a long shot). Any ideas on how I can modify this function to take into account leaf nodes, if that is, indeed, the problem? It's a little hard for me to follow.
My deleteByCopy() function:
Code:
void deleteByCopying(BinSearchNode<T>*& node)
{
BinSearchNode<T> *previous, *tmp = node;
if(node->right == 0)
node = node->left;
else if(node->left == 0)
node = node->right;
else if(node->right == 0 && node->left == 0)//my redneck attempt at a fix
{
delete tmp;
}
else
{
tmp = node->left;
previous = node;
while(tmp->right != 0)
{
previous = tmp;
tmp = tmp->right;
}
node->key = tmp->key;
if(previous == node)
previous->left = tmp->left;
else
previous->right = tmp->left;
}
delete tmp; //pow!!!!!!!!
}