What is needed in a C ++ binary tree class

I am mostly programmed in C. If I create a binary tree-like class in C ++, do I need to include a pointer to root as a property so that I can delete each node in the destructor, or is this usually done in a different way? And do I need a constructor?

Other than that, I only have data, left, right and methods, right?

+4
source share
3 answers

I am mostly programmed in C. If I create a binary tree-like class in C ++, do I need to include a pointer to root as a property so that I can delete every node in the destructor, or is it usually done in a different way?

You will want to clean up after the nodes if you allocate memory for them or you have leaks.

And do I need a constructor?

I would recommend four apocolypse riders: a constructor, a destructor, a copy constructor, and an assignment operator.

Other than that, I only have data, left, right and methods, right?

I will follow the STL example and create iterators: first depth, width, etc.

+2
source

Typically, C ++ objects are not intended to be removed from the container. Instead, the container (in this case, your binary tree) is considered the owner of the object. The destructor is called when the container decides to remove the node (presumably based on some request from your code).

Having a pointer to the root of the binary tree will violate encapsulation. Ideally, you would like your object to be inserted into another container, such as a vector. For example, the standard type std::string has no idea what it can be inserted into. Its destructor is only responsible for cleaning things within itself.

+4
source

Creating a pointer to the root directory of a node is usually necessary if you want it to execute correctly. This is easier if you want to designate "null" root as an empty tree.

Most objects should have constructors, in which case another binary search tree (for copying it) may be a worthy use of the constructor.

0
source

Source: https://habr.com/ru/post/1395144/


All Articles