搜索树定义
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
它的左右子树也分别为二叉搜索树
搜索树性质
实现
//类模板
//创建树节点
template <class K>
struct BSTreenode {
K _key;
BSTreenode<K>* _left;
BSTreenode<K>* _right;
BSTreenode(const K& key)
:_key(key)
, _left(nullptr)
, _right(nullptr)
{
}
};
template <class K>
class BSTree
{
//将节点typedef为Node方便理解和编程
typedef BSTreenode<K> Node;
public:
BSTree() = default;//强制生成默认构造
BSTree(const BSTree<K>& t)
{
//赋值构造
_root = Copy(t);
}
~BSTree()
{
Destory(_root);
}
BSTree<K>& operator=(BSTree<K> t)
{
//使用std的swap函数,交换指针指向
std::swap(_root, t._root);
return (*this);
}
bool Insert(const K& key)
{
if (_root == nullptr)
{
_root = new Node(key);
return true;
}
Node* parent = nullptr;
Node* cur = _root;
//先查找位置
while (cur)
{
parent = cur;
if (cur->_key < key)
{
cur = cur->_right;
}
else if (cur->_key > key)
{
cur = cur->_left;
}
else
return false;
}
cur = new Node(key);
if (parent->_key < key)
{
parent->_right = cur;
}
else
{
parent->_left = cur;
}
return true;
}
void Inorder()
{
_Inorder(_root);
cout << endl;
}
bool Find(const K& key)
{
Node* cur = _root;
while (cur)
{
if (cur->_key < key)
{
cur = cur->_left;
}
else if (cur->_key > key)
{
cur = cur->_right;
}
else
return true;
}
return false;
}
bool Erase(const K& key)
{
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
parent = cur;
if (cur->_key < key)
{
cur = cur->_left;
}
else if (cur->_key > key)
{
cur = cur->_right;
}
else
{
if (cur->_left == nullptr)
{//左子树为空
if (cur == _root)
{
_root = cur->_right;
}
else
{
if (parent->_left == cur)
{
parent->_left = cur->_right;
}
else
{
parent->_right = cur->_right;
}
}
}
else if (cur->_right == nullptr)
{//右子树为空
if (cur == _root)
{
_root = cur->_left;
}
else
{
if (parent->_left == cur)
{
parent->_left = cur->_left;
}
else
{
parent->_right = cur->_left;
}
}
}
else
{//都不为空
//左子树最右节点(最大)或右子树最左节点(最小)
parent = cur;
Node* subleft = cur->_right;
while (subleft->_left)
{
parent = subleft;
subleft = subleft->_left;
}
std::swap(cur->_key, subleft->_key);
if (parent->_left == subleft)
parent->_left = subleft->_right;
else
parent->_right = subleft->_right;
}
return true;
}
}
return false;
}
private:
void _Inorder(Node* root)
{
if (root == nullptr)
{
return;
}
_Inorder(root->_left);
cout << root->_key << " ";
_Inorder(root->_right);
}
//使用先序
void Destory(Node*& root)
{
if (root == nullptr)
return;
Destory(root->_left);
Destory(root->_right);
delete root;
root = nullptr;
}
Node* Copy(Node* root)
{
Node* newnode = new Node(root->_key);
newnode->_left = Copy(root->_left);
newnode->_right = Copy(root->_right);
return newnode;
}
Node* _root = nullptr;
};