Home > Back-end >  AVL-tree clearing
AVL-tree clearing

Time:11-27

I don't know, why _clear don't remove elements from a tree. Probably, needs to override destructor.

class Node {
    T _val;
    Node *_left;
    Node *_right;
    int _height;

    explicit Node(T _val = T()) : _val(_val), _left(nullptr), _right(nullptr), _height(1) {};

    friend class AVL_Tree<T>;
};

void AVL_Tree<T>::_clear(Node<T>*vertex) {
    if(vertex != nullptr) {
        _clear(vertex->_left);
        _clear(vertex->_right);
        delete vertex;
    }
    vertex = nullptr;
}

There are stay NULL linked nodes, why they don't delete?

CodePudding user response:

The problem is here:

AVL_Tree<T>::_clear(Node<T>*vertex)

You passed a pointer to Node by value, but you want to change the pointer and have the change propagate out of the function. The C way to do this is pass a reference to the pointer-to-Node:

AVL_Tree<T>::_clear(Node<T>*&vertex)

PS. Don't begin an identifier with an underscore. That's reserved for library implementers. So:

AVL_Tree<T>::clear(Node<T>*&vertex)
  • Related