14. C++二叉搜索树介绍以及实现
文章目录
一、二叉搜索树概念
二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:
- 若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
- 若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
- 它的左右子树也分别为二叉搜索树

二叉搜索树操作

int a[] = {8, 3, 1, 10, 6, 4, 7, 14, 13};
- 二叉搜索树的查找
a. 从根开始比较,查找,比根大则往右边走查找,比根小则往左边走查找。
b. 最多查找高度次,走到到空,还没找到,这个值不存在。 - 二叉搜索树的插入
插入的具体过程如下:
a. 树为空,则直接新增节点,赋值给root指针
b. 树不空,按二叉搜索树性质查找插入位置,插入新节点

- 二叉搜索树的删除
首先查找元素是否在二叉搜索树中,如果不存在,则返回, 否则要删除的结点可能分下面四种情况:
a. 要删除的结点无孩子结点
b. 要删除的结点只有左孩子结点
c. 要删除的结点只有右孩子结点
d. 要删除的结点有左、右孩子结点
看起来有待删除节点有4中情况,实际情况a可以与情况b或者c合并起来,因此真正的删除过程
如下:
- 情况b:删除该结点且使被删除节点的双亲结点指向被删除节点的左孩子结点–直接删除
- 情况c:删除该结点且使被删除节点的双亲结点指向被删除结点的右孩子结点–直接删除
- 情况d:在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点中,再来处理该结点的删除问题–替换法删除

二、二叉搜索树的实现
2.1 定义树节点
template <class K>
struct BSTNode
{
K _key;
BSTNode<K>* _left;
BSTNode<K>* _right;
BSTNode(const K& key)
: _key(key)
, _left(nullptr)
, _right(nullptr)
{
}
};
template<class K>
class BSTree
{
typedef BSTNode<K> Node;
public:
Node* _root = nullptr;
};
2.2 插入
- 首先判断根节点是否为空,为空直接插入
- 然后定义一个前驱节点,再定义当前节点,然后找要插入的位置
- 如果
cur比当前位置大往右走,比当前位置小往左走 - 最后还要判断要插入到左叶子还是右叶子,如果当前位置的值小于
val,就当在左面(要满足搜索二叉树的性质),否则就右面
bool Insert(const K& key)
{
if (_root == nullptr)
{
_root = new Node(key);
return true;
}
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
// 提前保存父节点
parent = cur;
// 比较->1.当前位置比key要大往右走
// 2. 当前位置比key要小往左走
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;
}
2.3 删除
首先找值,如果当前位置比val小就往左走,如果当前位置比val大就往右走,没有找到返回false
找到了后就删除,但是需要考虑几个问题:
左为空
右为空
左右都不为空
- 左为空
- 情况一:cur等于根,那么直接让我的根成为根的右子树
- 情况二:左为空,那么就让parent的左连接到cur的右

- 右为空
和左为空原理一样
- 情况一:cur等于根,那么直接让我的根成为根的左子树
- 情况二:右为空,那么就让parent的左连接到cur的左

- 左右都不为空
我们这里使用替换法
- 找左树的最大节点或者右子树的最小节点

bool Erase(const K& 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
{
// 找到了,进行删除
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* subParent = cur;
Node* sub = cur->_right;
while (sub->_left)
{
subParent = sub;
sub = sub->_left;
}
std::swap(sub->_key, cur->_key);
if (sub == subParent->_left)
subParent->_left = sub->_right;
else
subParent->_right = sub->_right;
delete sub;
}
return true;
}
}// while (cur)
return false;
}
2.4 查找
大于当前值往右走,小于往左走
bool Find(const K& 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;
}
2.5 遍历
void InOrder()
{
_InOrder(_root);
cout << endl;
}
void _InOrder(Node* root)
{
if (root == nullptr)
return;
_InOrder(root->_left);
std::cout << root->_key << " ";
_InOrder(root->_right);
}
三、递归版本&&全部代码
递归版本实现要注意的是要引用传参
namespace key
{
template <class K>
struct BSTNode
{
K _key;
BSTNode<K>* _left;
BSTNode<K>* _right;
BSTNode(const K& key)
: _key(key)
, _left(nullptr)
, _right(nullptr)
{
}
};
template<class K>
class BSTree
{
typedef BSTNode<K> Node;
public:
BSTree() = default; // 默认构造
~BSTree()
{
Destory(_root);
_root = nullptr;
}
BSTree(const BSTree<K>& t)
{
_root = Copy(t._root);
}
Node* Copy(Node* root)
{
if (root == nullptr)
return nullptr;
Node* newRoot = new Node(_root->_key);
newRoot->_left = Copy(root->_left);
newRoot->_right = Copy(root->_right);
return newRoot;
}
BSTree<K>& operator=(BSTree<K> k)
{
std::swap(_root, k._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;
// 比较->1.当前位置比key要大往右走
// 2. 当前位置比key要小往左走
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;
}
bool Erase(const K& 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
{
// 找到了,进行删除
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* subParent = cur;
Node* sub = cur->_right;
while (sub->_left)
{
subParent = sub;
sub = sub->_left;
}
std::swap(sub->_key, cur->_key);
if (sub == subParent->_left)
subParent->_left = sub->_right;
else
subParent->_right = sub->_right;
delete sub;
}
return true;
}
}// while (cur)
return false;
}
bool Find(const K& 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;
}
void InOrder()
{
_InOrder(_root);
cout << endl;
}
// ------------递归版本--------------
void FindR(const K& val)
{
return _FindR(_root, val);
}
bool InsertR(const K& val)
{
return _InsertR(_root, val);
}
bool EraseR(const K& val)
{
return _EraseR(_root, val);
}
private:
void _InOrder(Node* root)
{
if (root == nullptr)
return;
_InOrder(root->_left);
std::cout << root->_key << " ";
_InOrder(root->_right);
}
void Destory(Node*& root)
{
if (root == nullptr)
return;
Destory(root->_left);
Destory(root->_right);
delete root;
root = nullptr;
}
bool _FindR(Node* root, const K& val)
{
if (root == nullptr)
return false;
if (root->_key < val)
return _FindR(root->_right, val);
else if (root->_key > val)
return _FindR(root->_left, val);
else
return true;
}
// 这里注意是使用的引用
bool _InsertR(Node*& root, const K& val)
{
if (root == nullptr)
{
root = new Node(val);
return true;
}
if (root->_key < val)
return _InsertR(root->_right, val);
else if (root->_key > val)
return _InsertR(root->_left, val);
else
return false;
}
// 这里也要注意是用引用
bool _EraseR(Node*& root, const K& val)
{
if (root == nullptr)
return false;
if (root->_key < val)
return _EraseR(root->_right, val);
else if (root->_key > val)
return _EraseR(root->_left, val);
else
{
// 删除
if (root->_left == nullptr)
{
Node* del = root;
root = root->_right;
delete del;
return true;
}
else if (root->_right == nullptr)
{
Node* del = root;
root = root->_left;
delete del;
return true;
}
else
{
// 找替代节点
Node* subLeft = root->_right;
while (subLeft->_left)
{
subLeft = subLeft->_left;
}
std::swap(root->_key, subLeft->_key);
// 转换成在子树去递归删除
return _EraseR(root->_right, val);
}
}
return false;
}
Node* _root = nullptr;
};
}
四、二叉搜索树的性能分析
插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。
对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二 叉搜索树的深度的函数,即结点越深,则比较次数越多。
但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树:


问题:如果退化成单支树,二叉搜索树的性能就失去了。那能否进行改进,不论按照什么次序插入关键码,二叉搜索树的性能都能达到最优? AVL树和红黑树就可以上场了。
五、完善二叉搜索树
5.1 释放节点(析构)
- 一样需要使用引用传参
~BSTree()
{
Destory(_root);
_root = nullptr;
}
void Destory(Node*& root)
{
if (root == nullptr)
return;
Destory(root->_left);
Destory(root->_right);
delete root;
root = nullptr;
}
5.2 拷贝
递归拷贝左树和右树
Node* Copy(Node* root)
{
if (root == nullptr)
return nullptr;
Node* newRoot = new Node(_root->_val);
newRoot->_left = Copy(root->_left);
newRoot->_right = Copy(root->_right);
return newRoot;
}
- 写完这个拷贝构造后我们需要写一个默认构造
BSTree() = default;
5.3 赋值
BSTree<K>& operator=(BSTree<K> t)
{
std::swap(_root, t._root);
return *this;
}
六、二叉搜索树的应用
- K模型:K模型即只有key作为关键码,结构中只需要存储Key即可,关键码即为需要搜索到的值。
- 比如:给一个单词
word,判断该单词是否拼写正确,具体方式如下: - 以词库中所有单词集合中的每个单词作为key,构建一棵二叉搜索树
- 在二叉搜索树中检索该单词是否存在,存在则拼写正确,不存在则拼写错误。
- 比如:给一个单词
- KV模型:每一个关键码
key,都有与之对应的值Value,即<Key, Value>的键值对。该种方式在现实生活中非常常见:- 比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英文单词与其对应的中文
<word, chinese>就构成一种键值对; - 再比如统计单词次数,统计成功后,给定单词就可快速找到其出现的次数,单词与其出现次数就是
<word, count>就构成一种键值对。
- 比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英文单词与其对应的中文
七、全部源码以及KV模型的实现
BinarySearchTree.h
namespace key_value
{
template <class K, class V>
struct BSTNode
{
K _key;
V _value;
BSTNode<K, V>* _left;
BSTNode<K, V>* _right;
BSTNode(const K& key, const V& value)
:_key(key)
, _value(value)
, _left(nullptr)
, _right(nullptr)
{
}
};
template<class K, class V>
class BSTree
{
typedef BSTNode<K, V> Node;
public:
BSTree() = default; // 默认构造
~BSTree()
{
Destory(_root);
_root = nullptr;
}
void Destory(Node*& root)
{
if (root == nullptr)
return;
Destory(root->_left);
Destory(root->_right);
delete root;
root = nullptr;
}
Node* Copy(Node* root)
{
if (root == nullptr)
return nullptr;
Node* newRoot = new Node(_root->_val, root->_value);
newRoot->_left = Copy(root->_left);
newRoot->_right = Copy(root->_right);
return newRoot;
}
BSTree<K, V>& operator=(BSTree<K, V> k)
{
std::swap(_root, k._root);
return *this;
}
bool Insert(const K& key, const V& value)
{
if (_root == nullptr)
{
_root = new Node(key, value);
return true;
}
Node* parent = nullptr;
Node* cur = _root;
while (cur)
{
// 提前保存父节点
parent = cur;
// 比较->1. 当前位置比key要大往右走
// 2. 当前位置比key要大往右走
if (cur->_key < key)
cur = cur->_right;
else if (cur->_key > key)
cur = cur->_left;
else
return false;
}
// 找到位置了
cur = new Node(key, value);
if (parent->_key < key)
parent->_right = cur;
else
parent->_left = cur;
return true;
}
bool Erase(const K& 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
{
// 找到了,进行删除
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* subParent = cur;
Node* sub = cur->_right;
while (sub->_left)
{
subParent = sub;
sub = sub->_left;
}
std::swap(sub->_key, cur->_key);
std::swap(sub->_value, cur->_value);
if (sub == subParent->_left)
subParent->_left = sub->_right;
else
subParent->_right = sub->_right;
delete sub;
}
return true;
}
}// while (cur)
return false;
}
Node* Find(const K& key)
{
Node* cur = _root;
while (cur)
{
if (cur->_key < key)
cur = cur->_right;
else if (cur->_key > key)
cur = cur->_left;
else
return cur;
}
return nullptr;
}
void InOrder()
{
_InOrder(_root);
cout << endl;
}
private:
void _InOrder(Node* root)
{
if (root == nullptr)
return;
_InOrder(root->_left);
cout << root->_key << " " << " " << root->_value << endl;
_InOrder(root->_right);
}
Node* _root = nullptr;
};
}
BinarySearchTree.cpp
#include"BinarySearchTree.h"
//int main()
//{
// int a[] = { 8, 3, 1, 10, 6, 4, 7, 14, 13 };
// key::BSTree<int> b;
// for (auto e : a)
// {
// b.InsertR(e);
// }
// b.InOrder();
// // 删除
// b.EraseR(14);
// b.InOrder();
//
// b.EraseR(3);
// b.InOrder();
//
// b.EraseR(8);
// b.InOrder();
//
// for (auto e : a)
// {
// b.EraseR(e);
// b.InOrder();
// }
//
// return 0;
//}
#include<string>
void TestBSTree1()
{
// 输入单词,查找单词对应的中文翻译
key_value::BSTree<std::string, std::string> dict;
dict.Insert("string", "字符串");
dict.Insert("tree", "树");
dict.Insert("left", "左边、剩余");
dict.Insert("right", "右边");
dict.Insert("sort", "排序");
// 插入词库中所有单词
std::string str;
while (std::cin >> str)
{
key_value::BSTNode<std::string, std::string>* ret = dict.Find(str);
if (ret == nullptr)
{
std::cout << "单词拼写错误,词库中没有这个单词:" << str << std::endl;
}
else
{
std::cout << str << "中文翻译:" << ret->_value << std::endl;
}
}
}
void TestBSTree2()
{
// 统计水果出现的次数
std::string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜","苹果", "香蕉", "苹果", "香蕉" };
key_value::BSTree<std::string, int> countTree;
for (const auto& str : arr)
{
// 先查找水果在不在搜索树中
// 1、不在,说明水果第一次出现,则插入<水果, 1>
// 2、在,则查找到的节点中水果对应的次数++
key_value::BSTNode<string, int>* ret = countTree.Find(str);
// auto ret = countTree.Find(str);
if (ret == nullptr)
{
countTree.Insert(str, 1);
}
else
{
ret->_value++;
}
}
countTree.InOrder();
}
int main()
{
TestBSTree1();
TestBSTree2();
return 0;
}

浙公网安备 33010602011771号