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
{
template<class T>
struct Node
{
Node * parent;
template <class T>
struct Node
{
Node *parent;
T value;
T value;
std::unique_ptr<Node<T>> left;
std::unique_ptr<Node<T>> right;
std::unique_ptr<Node<T>> left;
std::unique_ptr<Node<T>> right;
Node(T const & _value, Node<T> * _parent)
: parent(_parent),
value(_value)
{}
};
bool IsLeaf() const
{
return left == nullptr && right == nullptr;
}
template<class T>
class Tree
{
private:
std::unique_ptr<Node<T>> root;
Node(T const &_value, Node<T> *_parent)
: parent(_parent),
value(_value)
{
}
};
public:
void Insert(T & value)
{
Node<T> * previousPtr = nullptr;
std::unique_ptr<Node<T>> & ptr = 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);
}
template <class T>
class Tree
{
private:
std::unique_ptr<Node<T>> root;
bool Contains(T const & value)
{
std::unique_ptr<Node<T>> & ptr = root;
while(ptr != nullptr)
{
if(ptr->value == value)
{
return true;
}
std::unique_ptr<Node<T>> & GetRightMostLeaf(std::unique_ptr<Node<T>> &localRoot)
{
std::unique_ptr<Node<T>> *nodePtr = &localRoot;
while ((*nodePtr)->right != nullptr)
{
nodePtr = &((*nodePtr)->right);
}
if(ptr->value > value)
{
ptr = ptr->left;
}
else
{
ptr = ptr->right;
}
}
return *nodePtr;
}
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