文章目录
template<class K,class V>
class BSTreeNode
{
public:
BSTreeNode<K,V>* left;
BSTreeNode<K,V>* right;
K _key;
V _value;
BSTreeNode(const K& key,const V& value)
:left(nullptr)
,right(nullptr)
,_key(key)
,_value(value)
{}
};
template<class K, class V>
class BSTree
{
typedef BSTreeNode<K, V> Node;
public:
bool Insert(const K& key, const V& value)
{
if (_root == nullptr)
{
_root = new Node(key,value);
return true;
}
Node* cur = _root;
Node* parent = nullptr;
while (cur)
{
parent = cur;
if (key < cur->_key)
{
cur = cur->left;
}
else if (key > cur->_key)
{
cur = cur->right;
}
else
{
return false;
}
}
cur = new Node(key,value);
if (key>parent->_key)
{
parent->right= cur;
}
else
{
parent->left = cur;
}
return true;
}
Node* Find(const K& key)
{
Node* cur = _root;
while (cur)
{
if (key < cur->_key)
{
cur = cur->left;
}
else if (key > cur->_key)
{
cur = cur->right;
}
else
{
return cur;
}
}
return nullptr;
}
bool Erase(const K& key)
{
Node* cur = _root;
Node* parent = nullptr;
while (cur)
{
if (key < cur->_key)
{
parent = cur;
cur = cur->left;
}
else if (key > cur->_key)
{
parent = cur;
cur = cur->right;
}
else
{
if (cur->left == nullptr)
{
if (cur == _root)
{
_root = cur->right;
}
else
{
if (cur == parent->left)
{
parent->left = cur->right;
}
else
{
parent->right = cur->right;
}
}
delete cur;
}
else if (cur->right == nullptr)
{
if (cur == _root)
{
_root = cur->left;
}
else
{
if (cur == parent->left)
{
parent->left = cur->left;
}
else
{
parent->right = cur->left;
}
}
delete cur;
}
else
{
Node* subleft = cur->right;
Node* subleft_p = cur;
while (subleft->left)
{
subleft_p = subleft;
subleft = subleft->left;
}
swap(cur->_key, subleft->_key);
swap(cur->_value, subleft->_value);
if (subleft == subleft_p->left)
{
subleft_p->left = subleft->right;
}
else
{
subleft_p->left = subleft->right;
}
delete subleft;
}
return true;
}
}
}
void _InOrder(Node* root)
{
if (root == nullptr)
return;
_InOrder(root->left);
cout << "key:" << root->_key << " value:" << root->_value << endl;
_InOrder(root->right);
}
void InOrder()
{
_InOrder(_root);
cout << endl;
}
private:
Node* _root = nullptr;
};