一.概念以及性质
二叉搜索树:一棵二叉树,可以为空;如果不为空,满足以下性质:
(1)若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
(2)若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
(3)它的左右子树也分别为二叉搜索树
1 .如果中序遍历,则是个升序
2 . 当你查找某个值(key)时,从根节点的值(val)开始,如果key > val,则去右子树查找;
如果key < val,则去左子树查找。(重复此步骤,直至找到)
二 . 实现二叉搜索树的增删查
1. 构建类
template<class T>
struct BSTreeNode //二叉树的每个节点
{
BSTreeNode<T>* _left;
BSTreeNode<T>* _right;
T _key;
BSTreeNode(const T& key)
:_left(nullptr)
,_right(nullptr)
,_key(key)
{}
};
//二叉树类
template<class T>
class BSTree
{
typedef BSTreeNode<T> Node;
public:
private:
Node* _root = nullptr;
};
2 . 插入
//插入
bool InsertK(const T& key)
{
Node* newnode = new Node(key);
if (_root == nullptr)
{
_root = newnode;
return true;
}
Node* parent = nullptr;//记录父亲节点,方便最后连接
Node* cur = _root;//找合适位置给newnode节点
while(cur)
{
parent = cur;
if (cur->_key < key)
{
cur = cur->_right;
}
else if (cur->_key > key)
{
cur = cur->_left;
}
else//相等是不能插入,因为不满足二叉搜索树的定义
{
return false;
}
}
//插入newnode
if (parent->_key < key)
{
parent->_right = newnode;
}
else
{
parent->_left = newnode;
}
return true;
}
3 . 打印(中序遍历)
//中序遍历
void Inorder()
{
_Inorder(_root);
cout << endl;
}
private:
void _Inorder(Node* _root)
{
if (_root == nullptr) return;
_Inorder(_root->_left);
cout << _root->_key << " ";
_Inorder(_root->_right);
}
Node* _root = nullptr;
//为什么这样写
//如果void Inorder(Node* _root);
//使用时,bt.Inorder(bt._root);
//但_root是私有的,这样访问是错的。
int main()
{
BSTree<int> bt;
int a[] = { 8,3,1,10,6,4,7,14,13 };
for (auto e : a)
{
bt.InsertK(e);
}
bt.Inorder();//打印出来是升序
return 0;
}
4 . 删
//删
bool EraseK(const T& key)
{
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
if (cur->_key < key)
{
parent = cur;
cur = cur->_right;
}
else if (cur->_key > key)
{
parent = cur;
cur = cur->_left;
}
//三种情况
else
{
//1.左子树为空
if (cur->_left == nullptr)
{
//删根节点
if (cur == _root) _root->_right;
else
{
if (cur == parent->_left)
{
parent->_left = cur->_right;
}
else
{
parent->_right = cur->_right;
}
}
}
//2.右子树为空
else if (cur->_right == nullptr)
{
if (cur == _root) _root->_left;
else
{
if (cur == parent->_left)
{
parent->_left = cur->_left;
}
else
{
parent->_right = cur->_left;
}
}
}
//3.两个孩子都有(替换法)
else
{
Node* parent = cur;
Node* subLeft = cur->_right;
while (subLeft->_left)
{
parent = subLeft;
subLeft = subLeft->_left;
}
swap(subLeft->_key, cur->_key);
if (subLeft == parent->_left)
parent->_left = subLeft->_right;
else
parent->_right = subLeft->_right;
}
return true;
}
}
return false;
}
5 . 查找
//查找
bool FindK(const T& key)
{
Node* cur = _root;
while (cur)
{
if (cur->_key < key)
{
cur = cur->_right;
}
else if (cur->_key > key)
{
cur = cur->_left;
}
else
{
return true;
}
}
return false;
}