How can I use a recursive function from inside a struct if I want to use a field from that struct as a parameter

Viewed 51

I have an AVL tree (I will not post all of the code because it wouldn't make sense), and I want to use a recursive function to delete it. The code looks something like this:

template <typename T>
struct AVL
{
    Nod<T>* root;
    ....
    void clear();
    ....
};

template<typename T>
inline void AVL<T>::clear()
{
    ....
    
    if (root == nullptr)
    {
        return;
    }

    clear(root->left); //I can't do this because clear doesn't take parameters
    clear(root->right);

    ....
}

In order to delete my nodes I want to recursively call this function, without taking parameters, it has to start from the root inside that struct everytime. But if I define the function without having parameters, I won't be able to call clear(root->left).

So, my question is:

how can I recursively call this function starting from the root field?

2 Answers

You can change it from clear(root->left) to root->left->clear() and the same with right node but you need to check whether they are nullptr before call clear

Create another private function that takes parameters:

template<typename T>
void AVL<T>::clear_helper(Node<T>* node)
{
    clear_helper(node->left); 
    clear_helper(node->right);
    ....
}


template<typename T>
inline void AVL<T>::clear()
{
    ....
    
    if (root == nullptr)
    {
        return;
    }
    clear_helper(root);
    

}
Related