Binary tree impl

This commit is contained in:
2019-04-28 16:09:36 +02:00
parent 30e9dc60b4
commit 554c94aa5b

View File

@@ -2,74 +2,130 @@
namespace BinaryTree namespace BinaryTree
{ {
template<class T> template <class T>
struct Node struct Node
{ {
Node * parent; Node *parent;
T value; T value;
std::unique_ptr<Node<T>> left; std::unique_ptr<Node<T>> left;
std::unique_ptr<Node<T>> right; std::unique_ptr<Node<T>> right;
Node(T const & _value, Node<T> * _parent) bool IsLeaf() const
: parent(_parent), {
value(_value) return left == nullptr && right == nullptr;
{} }
};
template<class T> Node(T const &_value, Node<T> *_parent)
class Tree : parent(_parent),
{ value(_value)
private: {
std::unique_ptr<Node<T>> root; }
};
public: template <class T>
void Insert(T & value) class Tree
{ {
Node<T> * previousPtr = nullptr; private:
std::unique_ptr<Node<T>> & ptr = root; std::unique_ptr<Node<T>> root;
while(ptr != nullptr)
{
previousPtr = ptr.get();
if(ptr->value > value)
{
ptr = ptr->left;
}
else
{
ptr = ptr->right;
}
}
ptr = std::make_unique<Node<T>>(value, previousPtr);
}
bool Contains(T const & value) std::unique_ptr<Node<T>> & GetRightMostLeaf(std::unique_ptr<Node<T>> &localRoot)
{ {
std::unique_ptr<Node<T>> & ptr = root; std::unique_ptr<Node<T>> *nodePtr = &localRoot;
while(ptr != nullptr) while ((*nodePtr)->right != nullptr)
{ {
if(ptr->value == value) nodePtr = &((*nodePtr)->right);
{ }
return true;
}
if(ptr->value > value) return *nodePtr;
{ }
ptr = ptr->left;
}
else
{
ptr = ptr->right;
}
}
return false; public:
} void Insert(T value)
{
Node<T> *previousPtr = nullptr;
std::unique_ptr<Node<T>> *rootPtr = &root;
while (*rootPtr != nullptr)
{
previousPtr = rootPtr->get();
if ((*rootPtr)->value > value)
{
rootPtr = &((*rootPtr)->left);
}
else
{
rootPtr = &((*rootPtr)->right);
}
}
*rootPtr = std::make_unique<Node<T>>(value, previousPtr);
}
void Delete(T const & value) bool Contains(T const value)
{ {
std::unique_ptr<Node<T>> *rootPtr = &root;
while (*rootPtr != nullptr)
{
if ((*rootPtr)->value == value)
{
return true;
}
} if ((*rootPtr)->value > value)
}; {
} rootPtr = &((*rootPtr)->left);
}
else
{
rootPtr = &((*rootPtr)->right);
}
}
return false;
}
void Delete(T const value)
{
std::unique_ptr<Node<T>> *rootPtr = &root;
while (*rootPtr != nullptr)
{
if ((*rootPtr)->value == value)
{
if ((*rootPtr)->IsLeaf())
{
rootPtr->release();
return;
}
if ((*rootPtr)->left == nullptr)
{
rootPtr->swap((*rootPtr)->right);
(*rootPtr)->right.release();
}
else if ((*rootPtr)->right == nullptr)
{
rootPtr->swap((*rootPtr)->left);
(*rootPtr)->left.release();
}
else
{
auto &replacementNode = GetRightMostLeaf((*rootPtr)->left);
rootPtr->swap(replacementNode);
replacementNode.release();
}
return;
}
if ((*rootPtr)->value > value)
{
rootPtr = &((*rootPtr)->left);
}
else
{
rootPtr = &((*rootPtr)->right);
}
}
}
};
} // namespace BinaryTree