其实所谓的二叉搜索树、二叉查找树、二叉排序树都是同一种东西,顾名思义Binary Search Tree是一种有利于查找数据的数据结构。其实在实际场景中用得最多的是红黑树,也是一种特殊的二叉平衡树;而二叉平衡树又是一种特殊的二叉查找树,也就是说,二叉查找树是一种范围很大的二叉树类别。当在二叉查找树中查找元素的时候,BSTree从根节点出发,通过比较查找目标与当前节点的数值,判断下一步的路径(左孩子或者右孩子),直至找到目标节点,如图所示:
二叉查找树必须满足以下三个条件:
1)若左子树不空,则左子树上所有结点的值均小于它的根节点的值;
2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值
3)左、右子树也分别为二叉排序树
当有新的元素插入BSTree或者删除BSTree中的元素时,必须对树的结构做实时调整以保证满足上面的三个条件。
下面为C++代码实现,包含创建、插入、查找、删除、遍历、返回极值等函数实现:
binarysearchtree.h
#ifndef BINSEARCHTREE
#define BINSEARCHTREE
#include <iostream>
#include <cmath>
using namespace std;
template<class T>
class Node{
public:
T key;
Node* left;
Node* right;
Node* parents;
Node(T _key,Node* _left,Node* _right,Node* _parents):key(_key),left(_left),right(_right),parents(_parents){}
};
template<class T>
class BSTree{
public:
Node<T> *root;
private:
void transplant(Node<T>* u,Node<T>* v);
public:
BSTree();
Node<T>* max(Node<T>* p);
Node<T>* min(Node<T>* p);
Node<T>* search(T key);
int get_height(Node<T>* p);
void insert(T key);
void remove(Node<T>* p);
void inorder_traversal(Node<T>* x);
};
//初始化
template<class T>
BSTree<T>::BSTree(){
root=NULL;
}
//子树最大节点
template<class T>
Node<T>* BSTree<T>::max(Node<T>* p){
Node<T>* x=p;
while(x->right!=NULL)
x=x->right;
return x;
}
//子树最小节点
template<class T>
Node<T>* BSTree<T>::min(Node<T>* p){
Node<T>* x=p;
while(x->left!=0)
x=x->left;
return x;
}
//查找
template<class T>
Node<T>* BSTree<T>::search(T key){
Node<T>* x;
x=root;
while(x!=NULL&&key!=x->key){
if(x->key<key)
x=x->right;
else
x=x->left;
}
return x;
}
//获取树的高度
template<class T>
int BSTree<T>::get_height(Node<T> *p){
if(p==NULL)
return 0;
else
return max(get_height(p->left),get_height(p->right));
}
//子树替换
template<class T>
void BSTree<T>::transplant(Node<T>* u,Node<T>* v){
if(u->parents==NULL)
v=root;
else{
if(u==u->parents->left)
u->parents->left=v;
else
u->parents->right=v;
}
if(v!=NULL)
v->parents=u->parents;
}
//插入
template<class T>
void BSTree<T>::insert(T key){
Node<T>* temp=new Node<T>(key,NULL,NULL,NULL);
Node<T>* y=NULL;
Node<T>* x=root;
while(x!=NULL){
y=x;
if(key<x->key)
x=x->left;
else
x=x->right;
}
temp->parents=y;
if(y==NULL)
root=temp;
else{
if(temp->key<y->key)
y->left=temp;
else
y->right=temp;
}
}
//删除
template<class T>
void BSTree<T>::remove(Node<T>* p){
if(p->left==NULL)
transplant(p,p->left);
else{
if(p->right==NULL)
transplant(p,p->right);
else{
Node<T>* y=min(p->right);//y为p的后继节点
if(y->parents!=p){
transplant(y,y->right);
y->right=p->right;
y->right->parents=y;
}
transplant(p,y);
y->left=p->left;
y->left->parents=y;
}
}
}
//中序遍历(顺序遍历)
template<class T>
void BSTree<T>::inorder_traversal(Node<T>* x){
if(x!=NULL){
inorder_traversal(x->left);
cout<<x->key<<" ";
inorder_traversal(x->right);
}
}
#endif // BINSEARCHTREE