二叉搜索树
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
若它的左子树不为空,则左子树上所有节点的值都小于根节点的值。
若它的右子树不为空,则右子树上所有节点的值都大于根节点的值。
它的左右子树也分别为二叉搜索树。
二叉搜索树的中序遍历是有序的。
二叉搜索树的查找
左子树比根结点小,右子树比根结点大,根据大小判断。如何查找
二叉搜索树的插入
找到插入的位置,记录父节点,左大右小。
二叉搜索树的删除
template <class T>
struct BSTNode
{
BSTNode(const T& data = T())
:_pLeft(null),
_pRight
{}
BSTNode<T>* _pLeft;
BSTNode<T>* _pRight;
T _data;
};
template<class T>
class BSTree
{
typedef BSTNode<T> Node;
BSTree()
:pRoot(nullptr)
{}
Node* find(int val)
{
Node* cur = pRoot;
if (pRoot == nullptr)
return nullptr;
while (cur)
{
if (cur->_data == val)
return cur;
else if (cur->_data > val)
cur = cur->_pRight;
else
cur = cur->_pLeft
}
}
bool insert(const T& val)
{
Node* node = new Node(val);
Node* cur = _pRoot;
Node* pPnode = nullptr;
if (cur == nullptr)
{
_pRoot = node;
return true;
}
while (cur)
{
pPnode = cur;
if (cur->_data < val)
cur = cur->_pLeft;
else if (cur->_data < val)
cur = cur->_pRight;
else
return false;
}
if (pPnode->_data < val)
pPnode->_pRight = val;
else
pPnode->_pLeft;
return true;
}
bool erase(const T& val)
{
Node* parent = nullptr;
Node* cur = _pRoot;
while (cur)
{
if (cur->_data > val)
{
parent = cur;
cur = cur->_pRight;
}
else if (cur->_data < val)
{
parent = cur;
cur = cur->_pLeft;
}
else
{
Node* del = cur;
if (cur->_pLeft == nullptr)
{
//如果当前节点,是根结点
if (parent == nullptr)
_pRoot = cur->_pRight;
else
{
if (cur == parent->_pLeft)
parent->_pLeft = cur->_pRight;
else
parent->_pRight = cur->_pRight;
}
}
else if (cur->_pRight == nullptr)
{
if (parent == nullptr)
_pRoot = cur->_pLeft;
else
{
if (cur == parent->_pLeft)
{
parent->_pLeft = cur->_pLeft;
}
else
parent->_pRight = cur->_pLeft;
}
}
else
{
Node* rpparent = cur;
Node* replace = cur->right;
while (replace->_pLeft)
{
pparent = replace;
replace = replace->_pLeft;
}
del = replace;
cur->_data = replace->_data;
rpparent->_pLeft = replace->_pRight;
}
delete del;
return true;
}
}
return false;
}
private:
Node* _pRoot;
};
来源:CSDN
作者:阿彬要成为大牛
链接:https://blog.csdn.net/qq_38833257/article/details/104575820