D
D
Danil Vaskevich2021-07-27 15:00:38
C++ / C#
Danil Vaskevich, 2021-07-27 15:00:38

How to delete a subtree completely?

I am writing a binary tree. It is necessary to implement the deletion of a node and all its child nodes, in other words, delete the entire subtree. I tried to do through recursion but something is not going as I expected. There are no errors, but the work just seems to be not being done. When outputting, you can see that all elements remain and nothing is deleted. Delete code:

template<typename T>
inline void BinTree<T>::deleteSubTree(Node<T>* node)
{
  if (node != nullptr)
  {
    deleteSubTree(node->left);
    deleteSubTree(node->right);
    node = nullptr;
  }
}

The output is implemented by two functions:
template<typename T>
inline void BinTree<T>::print() const
{
  if (root == nullptr)
  {
    cerr << "Error: Tree is empty\n";
    return;
  }
  else {
    cout << "Tree :\t";
    printNode(root);
    cout << endl;
  }
}

template<typename T>
inline void BinTree<T>::printNode(Node<T>* node) const
{
  if (node != nullptr)
  {
    printNode(node->left);
    cout << node->data << "\t";
    printNode(node->right);
  }
}

Node structure code:
template <typename T>
struct Node
{
  T data;
  Node* left, * right;
  Node(const  T& data = T(), Node* left = nullptr, Node* right = nullptr)
    : data(data), left(left), right(right)
  {}
};

Binary tree class code:
template <typename T>
class BinTree
{
public:
  Node<T>* getRoot() {
    return root;
  }
  BinTree() = default;
  void add(const T& data);
  bool isEmpty() const;
  void print() const;
  ~BinTree();
  bool check(T left, T right, T data);
  void deleteSubTree(Node<T>* node);
private:
  Node<T>* root = nullptr;
  void printNode(Node<T>* node) const;
};

main code:
int main() {
  BinTree<int> tree;
  tree.add(56);
  tree.add(34);
  tree.add(41);
  tree.add(65);
  tree.add(64);
  tree.print();
  cout << "\n========================AFTER=DELETION============================\n";
  tree.deleteSubTree(tree.getRoot()->left);
  tree.print();
}

Most likely, I incorrectly implemented the deletion in the code, so I hope you will correct me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-07-27
@wataru

node = nullptr;
This code overwrites the value of the node pointer, which is a function argument passed by value. In fact, you are overwriting a local variable.
Also, your function tries to overwrite all pointers with zeros, but it doesn't do it anywhere delete- that's why you have a memory leak there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question