vendredi 5 février 2021

C++ delete node and its child nodes

Please help me. I am stuck at this. What am I trying to do: Binary search tree. I am a C# developer and I learn C++ for about 2 weeks, therefore don't be so harsh with me and that's why pointers are still difficult for me.

I have a struct Node

struct Node
    {
        int Value;

        Node* _LeftNode;
        Node* _RightNode;

        Node(int value)
            : Value(value), _LeftNode(NULL), _RightNode(NULL)
        {
        }
    }; 

and a Delete() function in BinarySearchTree.cpp

void BinarySearchТрее::Delete(Node* node)
{
    if (node)
    {
        Delete(node->_LeftNode);
        Delete(node->_RightNode);
        delete(node);
        node = NULL;
    }
}

I want to delete the node and all of its child nodes. When i first step in the recursion... For example: Enter the recursion

I have two child nodes with values 10 and 19. With recursion i delete the nodes and set the pointers to NULL. NULL node

And here is the problem: When i came out from the recursion the nodes are not NULL, but something strange. After recursion

And this is my problem. Why when i am in the recursion and i NULL the pointer everything is fine, but when i come out the pointer is something else.

Aucun commentaire:

Enregistrer un commentaire