二叉树搜索树(BST)
二叉搜索树是一种二叉树,是应用非常广泛的一种二叉树,英文简称为BST。又称为:二叉查找树、二叉排序树
BST的特点
二叉树搜索树特点
- 任意一个节点的值都大于其左子树所有节点的值
- 任意一个节点的值都小于其右子树所有节点的值
SBT的接口
bool add(const T& x)
bool remove(const T& x)
bool contains(const T& x)
bool empty()
size_t size()
C++实现
#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
template<class T>
class BinarySearchTree
{
struct TreeNode
{
T _val;
TreeNode* _left;
TreeNode* _right;
TreeNode* _parent;
TreeNode(const T& val, TreeNode* parent = nullptr) :
_val(val), _left(nullptr), _right(nullptr), _parent(parent)
{}
};
public:
bool add(const T& x)
{
if (_root == nullptr)
{
_root = new TreeNode(x);
_size++;
return true;
}
TreeNode* cur = _root;
while (cur)
{
if (cur->_val > x)
{
if (cur->_left)
cur = cur->_left;
else
{
cur->_left = new TreeNode(x, cur);
_size++;
return true;
}
}
else if (cur->_val < x)
{
if (cur->_right)
cur = cur->_right;
else
{
cur->_right = new TreeNode(x, cur);
_size++;
return true;
}
}
else
return false;
}//end of while
return false;
}
bool remove(const T& x)
{
if (empty()) return false;
if (size() == 1)
{
_size--;
delete _root;
_root = nullptr;
return true;
}
TreeNode* cur = _root;
bool find = false;
while (cur)
{
if (cur->_val < x)
cur = cur->_right;
else if (cur->_val > x)
cur = cur->_left;
else
{
find = true;
break;
}
}//end fo while
if (!find) return false; //没找到直接返回
if (cur->_left && cur->_right)
{
TreeNode* prev = cur->_left;
while (prev && prev->_right)
prev = prev->_right;
cur->_val = prev->_val;
cur = prev;
}
if (cur->_left || cur->_right)
{
TreeNode* child = cur->_left ? cur->_left : cur->_right;
if (cur->_parent)
{
if (cur->_parent->_left == cur)
{
cur->_parent->_left = child;
child->_parent = cur->_parent;
}
else {
cur->_parent->_right = child;
child->_parent = cur->_parent;
}
}
else
{
_root = child;
child->_parent = nullptr;
}
}
else
{
if (cur->_parent->_left == cur)
cur->_parent->_left = nullptr;
else
cur->_parent->_right = nullptr;
}
_size--;
delete cur;
return true;
}
bool contains(const T& x)
{
if (empty()) return false;
TreeNode* cur = _root;
while (cur)
{
if (cur->_val > x)
cur = cur->_left;
else if (cur->_val < x)
cur = cur->_right;
else
return true;
}//end of while
return false;
}
bool empty()
{
return _root == nullptr;
}
size_t size()
{
return _size;
}
private:
TreeNode* _root = nullptr;
size_t _size = 0;
};
复杂度分析
最优情况下增删改查的时间复杂度为O(logN)
最坏情况下,BST就变成了链表,时间复杂度退化为O(N)