I'm trying to write a function for my binary tree class, which deletes all node with only one child. My teacher said, I should use a pointer to pointer to do it. But I have some problems. My function doesn't do it right. I used a function for deleting a node by its key from the binary tree, which worked well:
bool remove(int iKey) {
Node** pTmp = &pRoot;
//searching for a key in the tree
...
//there's no right child
Node* pNew = nullptr;
pNew = (*pTmp)->m_pLeft;
delete *pTmp;
*pTmp = pNew;
return true;
...
}
Here's my function for removing one child node:
void BinTree::deleteSingle(Node* root)
{
if (root != nullptr)
{
if (root->getLeft() != nullptr)
deleteSingle(root->getLeft());
if (root->getRight() != nullptr)
deleteSingle(root->getRight());
//there's only left child
if (root->getLeft() != nullptr && root->getRight() == nullptr)
{
//1 version: this doesn't work for me
/*Node** tmp = &root;
Node* child = root->pLeft;
delete *tmp;
*tmp = child;*/
//2 version: but this workes great
Node* child = root->pLeft;
delete root;
*root = *child;
}
//if there's only right child - remove the node analogical
}
}
Here's my destructor for Node class and an assignment operator. The BinTree class has Node* pRoot;
as a private member.
Node::~Node()
{
pLeft = nullptr;
pRight = nullptr;
}
Node& Node::operator=(const Node& node)
{
key = node.key;
data = node.data;
pLeft = nullptr;
pRight = nullptr;
if (node.pLeft != nullptr)
pLeft = new Node(node.pLeft->key, node.pLeft->data);
if (node.pRight != nullptr)
pRight = new Node(node.pRight->key, node.pRight->data);
return *this;
}
I don't understand why I do need remove a node using pointer to pointer, if my 2 version works good and needs less memory. Maybe because I need also have a destructor and an assignment operator for the Node class? And I still can't understand, why my first version doesn't work and what should I do. I hope you could help me or show me some other correct method to delete one child nodes
__________________UPDATE_____________________
I've found out an other method to do it, but I'm not using pointer to pointer here (I'm still interested in it also, if anyone could show me it). Here I just copy the data and the pointers of the child and delete the child node.
if (root->getLeft() != nullptr && root->getRight() == nullptr)
{
Node* child = root->pLeft;
root->key = child->key;
root->data = child->data;
root->pLeft = child->pLeft;
root->pRight = child->pRight;
delete child;
}