Still pretty new to C++, I figured that the best place to start would be to program up some basic data structures. However, I'm encountering a problem in my Binary Search Tree's delete method. Below, I'm posting the skeleton deleteNum method (I stripped it, so it does almost nothing now), and my findNodeFromKey() methods.
void deleteNum(int key)
{
//If key is NOT in the BST, do nothing
//If key is in the BST, find its node p
//If p has no children, simply delete p
//If p has one child, that child should take p's place
//If p has two children . . .
BinarySearchTree* p = findNodeFromKey(key);
std::cout << p << std::endl;
std::cout << p->data << std::endl;
std::cout << std::endl;
}
BinarySearchTree* findNodeFromKey(int key)
{
if(data == key)
{
std::cout << "found " << key << std::endl;
std::cout << this << std::endl;
std::cout << this->data << std::endl;
returnthis;
}
elseif(data < key)
{
if(!rightChild){ return NULL; }
else {
std::cout << "search right child of " << data << " for " << key << std::endl;
rightChild->findNodeFromKey(key);
}
}
else
{
if(!leftChild) { return NULL; }
else {
std::cout << "search left child of " << data << " for " << key << std::endl;
leftChild->findNodeFromKey(key);
}
}
}
When I call BST->deleteNum(3) from my main method, here is the output I get (with added comments):
1 2 3 4 5 6 7
search left child of 35 for 3
search right child of 1 for 3
found 3
0x9d0c048 // value of the "this" pointer to be returned from findNodeFromKey()
3 // value of this->data. 3, as expected
0xb7fbc989 // value of the pointer p.
1082853003 // value of p->data. Was expecting this to be 3.
I know this is probably a very simple question, but when I made the assignment BinarySearchTree* p = findNodeFromKey(key); in deleteNum(), shouldn't p be pointing to the object returned? So shouldn't p->value = 3? What am I missing here?
And there it is. *smacks head* Here's the new output, with guestgalkin's advised changes in place
1 2 3 4 5 6 7
search left child of 35 for 3
search right child of 1 for 3
found 3
0x88b3048
3
0x88b3048
3 // p->value = 3 !
I guess that I was expecting it to return correctly because the return statement was included in the if(data == key) clause. Sometimes you just need another set of eyes.