I have already some sort of solution for the problem:
Given an integer N, construct all possible binary search trees with N nodes.
except that I include trees with root the minimum and maximum value but this is not my main concern. I want to put emphasis into correctly using the move semantics and memory management in C++ (as a learning exercice).
My solution is:
#include <vector>
struct Node{
int value;
Node *left = nullptr;
Node *right = nullptr;
};
std::vector<Node*> createListNodes(int min, int max)
{
// ordered vector with i.e. {0,1,2,3,4}
Node *node = new Node;
if (min == max)
{
node->value = min;
return std::vector<Node*> {node}; // it is a leaf node
}
std::vector<Node*> alterantive{};
for (int i=min; i<=max; i++)
{
auto left = createListNodes(min,i-1); // for the left side
auto right = createListNodes(i+1,max); // for the left side
if (left.size() == 0) // if node i has just one child and it is in the right
{
for (auto elem_right : right)
{
alterantive.emplace_back(new Node{i,nullptr,elem_right});
}
}
else if (right.size() == 0) // if node i has just one child and it is in the left
{
for (auto elem_left : left)
{
alterantive.emplace_back(new Node{i,elem_left,nullptr});
}
}
for (auto elem_left : left)
{
for (auto elem_right : right)
{
alterantive.emplace_back(new Node{i,elem_left,elem_right});
}
}
}
return alterantive;
}
int main()
{
int N = 4;
std::vector<Node*> combinations = createListNodes(0, N);
}
So would like to know:
- Improvements I could made to my basic design, I would prefer not to use smart pointers yet but the raw ones, to make it more memory efficient (copying less values from one side to the other ...)
- General improvements in the code, even though my main focus is on memory management, memory leaks ...