I am a hobbyist programmer trying find the appropriate place to put unique_ptr
in my binary tree. Originally, I used unique_ptr
for the left and right children, but that "meant" that each node "owned" each subsequent node. I have been told in a previous post that the tree should own its nodes. This is my solution to the problem: all of the trees nodes are stored in a vector of unique pointers and unique_ptr::get
is used to extract the raw pointers which are used in the usual manner (example add).
#include "pch.h"
#include <iostream>
#include <sstream>
#include <string>
#include <memory>
#include <vector>
#include <unordered_map>
class Node
{
public:
Node(int data = 0) : data_(data), left_child(nullptr),
right_child(nullptr) {}
int data_;
Node *left_child;
Node *right_child;
};
class Tree
{
public:
Tree(int data = 0) {
store.emplace_back(std::make_unique<Node>(data));
root = store.at(0).get();
}
void add(int data) {
Node *index = root;
while (true) {
if (data == index->data_) {
std::stringstream ss;
ss << data << " already exists\n";
throw std::invalid_argument(ss.str());
}
if (data < index->data_) {
if (index->left_child != nullptr) {
index = index->left_child;
continue;
}
std::unique_ptr<Node> temp = std::make_unique<Node>(data);
index->left_child = temp.get();
store.push_back(std::move(temp));
return;
}
if (index->right_child != nullptr) {
index = index->right_child;
continue;
}
std::unique_ptr<Node> temp = std::make_unique<Node>(data);
index->right_child = temp.get();
store.push_back(std::move(temp));
return;
}
}
private:
std::vector<std::unique_ptr<Node>> store;
Node* root;
};
Removing a node seems like it will be painfully slow. Find the value in the tree (fast), find the pointer in the std::vector
(slow), remove the entry from the vector, and finally trim the pointer from the parent. Am I on the right track? If not, hints would be welcome.